Netty 4 multiple client(Netty 4 多客户端)
问题描述
我需要让客户端能够建立许多连接.我使用 Netty 4.0.不幸的是,所有现有示例都没有显示如何创建大量连接.
I need to make the client is able to make many connections. I use Netty 4.0. Unfortunately all existing examples do not show how to create a lot of connections.
public class TelnetClient {
private Bootstrap b;
public TelnetClient() {
b = new Bootstrap();
}
public void connect(String host, int port) throws Exception {
try {
b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class).remoteAddress(host, port).handler(new TelnetClientInitializer());
Channel ch = b.connect().sync().channel();
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
String line = in.readLine();
if (line == null) break;
lastWriteFuture = ch.write(line + "
");
if (line.toLowerCase().equals("bye")) {
ch.closeFuture().sync();
break;
}
}
if (lastWriteFuture != null) lastWriteFuture.sync();
} finally {
b.shutdown();
}
}
public static void main(String[] args) throws Exception {
TelnetClient tc = new TelnetClient();
tc.connect("127.0.0.1", 1048);
tc.connect("192.168.1.123", 1050);
//...
}
}
这是正确的决定吗?还是会更好?
Is this the correct decision? or could it be better?
推荐答案
是的,它几乎是正确的.你唯一必须改变的是在每次连接时创建 NioEventLoopGroup.
Yes its almost correct.. The only thing you MUST change is the creation of NioEventLoopGroup on every connect.
NioEventLoopGroup 实例很昂贵,因此应该共享它们.创建一个实例并共享它,每次都将相同的实例传递给 Bootstrap.group(...)..
NioEventLoopGroup instances are expensive so they should be shared. Create one instance and share it, by pass the same instance to the Bootstrap.group(...) everytime..
这篇关于Netty 4 多客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Netty 4 多客户端
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01