Fork me on GitHub

netty4.0 Server和Client的通信

netty4.0 Server和Client的通信

创建一个maven项目

添加Netty依赖

    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.16.Final</version>
    </dependency>

Server端开发

public class HelloServer {
    public void start(int port) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();//注意和 client 的区别
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        serverBootstrap.group(boosGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);//注意和 client 端的区别,client 端是 NioSocketChannel
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new HelloServerInHandler());
                    }
                });
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        try {
            // 绑定端口,开始接收进来的连接
            ChannelFuture f = serverBootstrap.bind(port).sync();
            // 等待服务器  socket 关闭 。
            // 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        HelloServer helloServer = new HelloServer();
        int port = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        helloServer.start(port);
    }
}

server 消息处理

@ChannelHandler.Sharable
public class HelloServerInHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            ByteBuf inMsg = (ByteBuf) msg;
            byte[] bytes = new byte[inMsg.readableBytes()];
            inMsg.readBytes(bytes);
            String inStr = new String(bytes);
            System.out.println("client send msg: " + inStr);

            String response = "i am ok!";
            ByteBuf outMsg = ctx.alloc().buffer(4 * response.length());
            outMsg.writeBytes(response.getBytes());
            ctx.writeAndFlush(outMsg);
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}

client 开发

public class HelloClient {
    public void connect(String host, int port) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap(); //注意和 server 的区别
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);//注意和 server 端的区别,server 端是 NioServerSocketChannel
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new HelloClientIntHandler());
            }
        });
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        try {
            // Start the client.
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 等待服务器  socket 关闭 。
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        HelloClient client = new HelloClient();
        client.connect("127.0.0.1", 8080);
    }
}

client 消息处理

public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {

    // 连接成功后,向server发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("connected server. start send msg.");
        String msg = "r u ok?";
        ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
        encoded.writeBytes(msg.getBytes());
        ctx.writeAndFlush(encoded);
    }

    // 接收server端的消息,并打印出来
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf result = (ByteBuf) msg;
            byte[] serverMsg = new byte[result.readableBytes()];
            result.readBytes(serverMsg);
            System.out.println("Server said:" + new String(serverMsg));
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

测试

分别启动server端和client端

server端会输出如下内容:

client send msg: r u ok?

client端会输出如下内容:

Server said:i am ok!
posted @ 2017-10-27 12:36  秋楓  阅读(522)  评论(0编辑  收藏  举报