Netty-5-客户端的创建并且接受服务端的数据

网友投稿 563 2022-11-19

Netty-5-客户端的创建并且接受服务端的数据

Netty-5-客户端的创建并且接受服务端的数据

下面的示例内容是创建了两个客户端,以NetAssist作为服务端,服务端向哪个客户端发信息,哪个客户端就把自己的IP地址返回给服务端

1.首先创建一个InboundHandler,来处理输入进来的信息

public class MyClientHandler1 extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf bb = (ByteBuf) msg; int len = bb.readableBytes(); byte[] bytes = new byte[len]; bb.readBytes(bytes); System.out.println("读到的内容:" + new String(bytes, "utf-8")); String result = ctx.channel().localAddress().toString(); ByteBuf rr = Unpooled.copiedBuffer(result.getBytes()); ctx.writeAndFlush(rr); }}

2.创建一个客户端,启动main方法

public class TestClient1 { public static void main(String[] args) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new MyClientHandler1()); ChannelFuture f = b.connect("127.0.0.1", 9999).sync(); f.channel().closeFuture().sync(); }}

3.再创建一个客户端,也启动main方法

public class TestClient2 { public static void main(String[] args) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new MyClientHandler1()); ChannelFuture f = b.connect("127.0.0.1", 9999).sync(); f.channel().closeFuture().sync(); }}

其实和之前的文章没什么太大区别,只不过这是客户端,之前的是服务端,值得一提的是文章并没有演示客户端连接服务端的时候,客户端先发送到服务端,因为和之前的文章是一样的,可以直接从active方法中进行这一操作

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Netty-1-一个简单的服务器实例
下一篇:浅谈synchronized加锁this和class的区别
相关文章

 发表评论

暂时没有评论,来抢沙发吧~