下面的示例內容是創建了兩個客戶端,以NetAssist作為服務端,服務端向哪個客戶端發信息,哪個客戶端就把自己的IP地址返回給服務端
1.首先創建一個InboundHandler,來處理輸入進來的信息
public class MyClientHandler1 extends ChannelInboundHandlerAdapter {@Overridepublic 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();}
}
使用網絡助手作為服務端進行調試,將客戶端選擇1圖所示,點擊發送,會返回1圖連接的客戶端地址,客戶端選擇2圖所示,點擊發送,會返回2圖連接的客戶端地址
其實和之前的文章沒什么太大區別,只不過這是客戶端,之前的是服務端,值得一提的是文章并沒有演示客戶端連接服務端的時候,客戶端先發送到服務端,因為和之前的文章是一樣的,可以直接從active方法中進行這一操作
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态