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

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

netty4.0 Server和Client的通信

创建一个maven项目

添加Netty依赖

io.netty
netty-all
4.1.16.Final

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
() { 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.Sharablepublic 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
() { 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!

转载于:https://www.cnblogs.com/rwxwsblog/p/7742597.html

你可能感兴趣的文章
Nginx(二)
查看>>
CF #329 D
查看>>
Android中pendingIntent的深入理解
查看>>
地图之CLLocationManager的使用 定位功能使用
查看>>
AsyncTask 之怎样使用
查看>>
NancyFX 第九章 Responses(响应对象)
查看>>
C#WinForm 窗体回车替换Tab
查看>>
深入理解java虚拟机(5)---字节码执行引擎
查看>>
jquery之别踩白块游戏的实现
查看>>
从今天开始写博客
查看>>
利用python进行泰坦尼克生存预测——数据探索分析
查看>>
pow log 与 (int)
查看>>
索引的分类--B-Tree索引和Hash索引
查看>>
C++ 用循环链表解决约瑟夫环问题
查看>>
POJ 2031 Building a Space Station (计算几何+最小生成树)
查看>>
hdu 1394 Minimum Inversion Number
查看>>
AcCoder Contest-115 D - Christmas
查看>>
Java基础知识(JAVA之泛型)
查看>>
css3动画与2D、3D之间的转换
查看>>
[Android]仿新版QQ的tab下面拖拽标记为已读的效果
查看>>