netty4.0 Server和Client的通信

简介: netty4.0 Server和Client的通信创建一个maven项目添加Netty依赖 io.netty netty-all 4.1.16.Final Server端开发public class HelloServer { p...

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!
相关文章
|
3月前
|
网络协议
【Netty 网络通信】Socket 通信原理
【1月更文挑战第9天】【Netty 网络通信】Socket 通信原理
|
3月前
|
Java Maven
【Netty 网络通信】启动通信服务端
【1月更文挑战第9天】【Netty 网络通信】启动通信服务端
|
2月前
|
网络协议
Netty实现TCP通信
Netty实现TCP通信
41 0
|
4月前
|
移动开发 JavaScript 网络协议
SpringBoot:Netty-SocketIO + VUE:SocketIO实现前后端实时双向通信
SpringBoot:Netty-SocketIO + VUE:SocketIO实现前后端实时双向通信
128 0
|
9天前
|
移动开发 网络协议 Java
通信密码学:探秘Netty中解码器的神奇力量
通信密码学:探秘Netty中解码器的神奇力量
17 0
|
3月前
|
负载均衡 Java 调度
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
经过阅读《【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)》,相信您已经对网络通信框架的网络通信层的实现原理和协议模型有了一定的认识和理解。
40 0
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
|
3月前
|
Dubbo Java 应用服务中间件
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
今天,我要向大家实现一个基于Netty实现的高性能远程通信框架!这个框架利用了 Netty 的强大功能,提供了快速、可靠的远程通信能力。 无论是构建大规模微服务架构还是实现分布式计算,这个分布式通信框架都是一个不可或缺的利器。
61 2
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
|
3月前
|
前端开发 Java Maven
【Netty 网络通信】启动客户端连接服务端实现通信
【1月更文挑战第9天】【Netty 网络通信】启动客户端连接服务端实现通信
|
3月前
|
编解码
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战_自定义长度分包编解码码器
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战_自定义长度分包编解码码器
46 0
|
3月前
|
网络协议
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战
46 0