1:导入maven坐标或者引入jar包
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha1</version> </dependency>
2:服务端和客户端的编写
2.1 服务端编写
服务端启动的辅助对象是ServerBootstrap,
ServerBootstrap b = new ServerBootstrap();
然后给他绑定loopGroup、设置通道类型,以及设置处理消息的handler
EventLoopGroup parentGroup = new NioEventLoopGroup(); EventLoopGroup childGroup = new NioEventLoopGroup(); b.group(parentGroup,childGroup).channel(NioServerSocketChannel.class).childHandler( new ChannelInitializer<SocketChannel>(){ protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() { protected void messageReceived( ChannelHandlerContext channelHandlerContext,Object o) throws Exception { ByteBuf byteBuf = (ByteBuf) o; byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); System.out.println("read info === "+new String(bytes)); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("========active"); } }); } });
ServerBootstrap 的参数什么的设置好之后就是绑定端口进行异步启动server
ChannelFuture future = b.bind(8085).sync(); future.channel().closeFuture().sync();
2.2client端编写
client端使用的辅助类是Bootstrap,先出示Bootstrap
Bootstrap b = new Bootstrap();
然后和服务端差不多,设置EventLoopGroup、通道类型、消息处理的handler
b.group(new NioEventLoopGroup).channel
(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() { protected void messageReceived(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { System.out.println("client====read "+o); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("=========activ client"); ByteBuf byteBuf = Unpooled.buffer("test client Info".length()); byteBuf.writeBytes("test client Info".getBytes()); ctx.writeAndFlush(byteBuf); } }); } });
然后进行连接服务端,并异步处理
ChannelFuture future = b.connect("localhost",8085).sync(); future.channel().closeFuture().sync();
需要注意的是,在处理消息的handler内如果没有添加其他的解码、编码的处理器,则需要把信息转成ByteBuf对象然后再写出去