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 消息處理bootstrap

@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端socket

server端會輸出以下內容:maven

client send msg: r u ok?

client端會輸出以下內容:ide

Server said:i am ok!
相關文章
相關標籤/搜索