Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

netty Client 多IP #8

Closed
Duanzq-GIT opened this issue Oct 21, 2019 · 1 comment
Closed

netty Client 多IP #8

Duanzq-GIT opened this issue Oct 21, 2019 · 1 comment

Comments

@Duanzq-GIT
Copy link

使用netty client 同时连接多个服务器,并进行消息的收发且互不干扰,大神 有封装,实现思路吗?

@waylau
Copy link
Owner

waylau commented Jun 10, 2020

@Duanzq-GIT
起多个Bootstrap 就可以了,示例如下:

EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast("decoder", new MyDecoder());
					ch.pipeline().addLast("encoder", new MyEncoder());
					ch.pipeline().addLast(new MyClientHandler());

				}
			});

			Bootstrap b2 = new Bootstrap();
			b2.group(workerGroup);
			b2.channel(NioSocketChannel.class);
			b2.option(ChannelOption.SO_KEEPALIVE, true);
			b2.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast("decoder", new MyDecoder());
					ch.pipeline().addLast("encoder", new MyEncoder());
					ch.pipeline().addLast(new MyClientHandler());

				}
			});
			// 启动客户端
			ChannelFuture f = b2.connect(host, port).sync();
			ChannelFuture f2 = b2.connect(host, port).sync();

			while (true) {

				// 发送消息给服务器
				Msg msg = new Msg();
				MsgHeader msgHeader = new MsgHeader();
				msgHeader.setMsgType(MsgType.EMGW_LOGIN_REQ.getValue());
				String body = "床前明月光,疑是地上霜。举头望明月,低头思故乡。";

				byte[] bodyBytes = body.getBytes(Charset.forName("utf-8"));
				int bodySize = bodyBytes.length;
				msgHeader.setLen(bodySize);
				msg.setMsgHeader(msgHeader);
				msg.setBody(body);

				f.channel().writeAndFlush(msg);
				f2.channel().writeAndFlush(msg);
				Thread.sleep(2000);
			}
		} finally {
			workerGroup.shutdownGracefully();
		}

@waylau waylau closed this as completed Jun 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants