下面的示例內容是創建了兩個客戶端,以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();
}
}
使用網絡助手作爲服務端進行調試,將客戶端選擇1圖所示,點擊發送,會返回1圖連接的客戶端地址,客戶端選擇2圖所示,點擊發送,會返回2圖連接的客戶端地址
其實和之前的文章沒什麼太大區別,只不過這是客戶端,之前的是服務端,值得一提的是文章並沒有演示客戶端連接服務端的時候,客戶端先發送到服務端,因爲和之前的文章是一樣的,可以直接從active方法中進行這一操作