Netty Server Demo

Maven添加依赖

1
2
3
4
5
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.29.Final</version>
</dependency>

Server Demo

模拟请求/响应model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.zsr.test.netty;
public class RequestData {
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
}
// return RequestData inValue * 2
public class ResponseData {
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
}

服务端对请求解码

1
2
3
4
5
6
7
8
public class ServerRequestDecoder extends ReplayingDecoder<RequestData> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
RequestData data = new RequestData();
data.setIntValue(in.readInt());
out.add(data);
}
}

服务端对响应编码

1
2
3
4
5
6
public class ServerResponseEncoder extends MessageToByteEncoder<ResponseData> {
@Override
protected void encode(ChannelHandlerContext ctx, ResponseData msg, ByteBuf out) throws Exception {
out.writeInt(msg.getIntValue());
}
}

服务端具体业务处理

1
2
3
4
5
6
7
8
9
10
public class ServerProcessingHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
RequestData requestData = (RequestData) msg;
ResponseData responseData = new ResponseData();
responseData.setIntValue(requestData.getIntValue() * 2);
ctx.writeAndFlush(responseData);
System.out.println("server receive request: " + requestData.getIntValue());
}
}

启动服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class NettyTestServer {
public static void main(String[] args) throws Exception {
new NettyTestServer(8080).start();
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ServerRequestDecoder(), new ServerResponseEncoder(),
new ServerProcessingHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).sync();
System.out.println(
NettyTestServer.class.getName() + " started and listen on " + channelFuture.channel().localAddress());
channelFuture.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}

参考

Introduction to Netty

Netty的那点事儿

热评文章