public Server() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128).handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new JsonObjectDecoder());//JSon解码器。
sc.pipeline().addLast(new StringEncoder());// 发送字符串的编码器。
sc.pipeline().addLast(new StringDecoder());// 接收到字符串的解码器。
sc.pipeline().addLast(new MyChannelHandlerAdapter());
}
});
// 绑定端口,开始接收进来的连接。
ChannelFuture cf = b.bind(SERVER_PORT).sync();
// 等待服务器关闭Socket。
cf.channel().closeFuture().sync();
}
private class MyChannelHandlerAdapter extends ChannelHandlerAdapter {
private final Logger logger = Logger.getLogger(MyChannelHandlerAdapter.class.getName());
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(“连接激活”);
ctx.writeAndFlush(