博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
netty4.0 Server和Client的通信
阅读量:7009 次
发布时间:2019-06-28

本文共 4190 字,大约阅读时间需要 13 分钟。

创建一个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!
本文转自秋楓博客园博客,原文链接:http://www.cnblogs.com/rwxwsblog/p/7742597.html,如需转载请自行联系原作者
你可能感兴趣的文章
Win10 UWP系列:更新UWP时注意的问题——TargetDeviceFamily
查看>>
C++代码重构——从C global到C++ template
查看>>
C语言 const与指针
查看>>
在Android Studio进行“简单配置”单元测试(Android Junit)
查看>>
vim中末行去掉^M
查看>>
宏定义偷懒型set,get
查看>>
Python从MongoDB中按天读取数据并格式化日志
查看>>
Oracle-client支持exp|imp|rman
查看>>
postgresql如何维护WAL日志/归档日志
查看>>
PostgreSQL流复制
查看>>
Mac机装Win7后 启动只见鼠标怎么办
查看>>
Mac_OS_Sierra_10.12.6编译OpenJDK9
查看>>
Kubernetes-基于flannel的集群网络
查看>>
MS SQL自定义函数IsPositiveInteger
查看>>
pgsql 执行建库脚本时候出现ERROR: relation "xxx_id_seq" does not exist
查看>>
SQL FOR XML
查看>>
Vim as Python IDE on windows(转)
查看>>
《Web Services Testing with soapUI》书附带的例子下载
查看>>
Caffe + Ubuntu 14.04 64bit + CUDA 6.5 配置说明
查看>>
上传文件的方法
查看>>