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();
	}
}

使用网络助手作为服务端进行调试,将客户端选择1图所示,点击发送,会返回1图连接的客户端地址,客户端选择2图所示,点击发送,会返回2图连接的客户端地址
在这里插入图片描述
其实和之前的文章没什么太大区别,只不过这是客户端,之前的是服务端,值得一提的是文章并没有演示客户端连接服务端的时候,客户端先发送到服务端,因为和之前的文章是一样的,可以直接从active方法中进行这一操作

发布了157 篇原创文章 · 获赞 26 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u011624903/article/details/76851152
今日推荐