一个简单的Netty服务  接收什么信息就回复什么信息

总目录

Netty 5.x  1.netty服务器搭建

Netty 5.x 2.自定义编解码器

Maven依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha2</version>
</dependency>

创建服务 并绑定端口

public class Server extends Thread{
	private int port = -1;
	
	public Server(int port) {
		this.port = port;
	}
	
	@Override
	public void run() {
		bind(port);
	}
	
	private void bind(int port) {
		EventLoopGroup boss = new NioEventLoopGroup(1);
		EventLoopGroup work = new NioEventLoopGroup();

		ServerBootstrap bootstrap =  new ServerBootstrap();
		try {
			bootstrap.group(boss, work)
			.channel(NioServerSocketChannel.class)//注册factory
			.childHandler(new ChannelInitializer<Channel>() {//注册piepline
				@Override
				protected void initChannel(Channel sc) throws Exception {//初始化连接
					sc.pipeline().addLast(new ServerHandle());			//添加处理网络io类
				}
			})
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.TCP_NODELAY, true)//TCP无掩饰
			.childOption(ChannelOption.SO_KEEPALIVE,true);//清除死连接,维持活跃的
			ChannelFuture future = bootstrap.bind(port);
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
	}


}

网络io处理类(服务器信息处理器)

public class ServerHandle extends SimpleChannelInboundHandler<ByteBuf>{

	@Override
	protected void messageReceived(ChannelHandlerContext cx, ByteBuf message) throws Exception {
            byte[] b = new byte[message.readableBytes()];
            message.readBytes(b);
            System.out.println(new String(b));
            message.resetReaderIndex();//重置指针
            cx.write(message);
            cx.flush();
	}

}