[英]Netty 4 multiple client
我需要讓客戶端能夠建立許多連接。 我使用Netty 4.0。 不幸的是,所有現有示例都沒有顯示如何創建大量連接。
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 + "\r\n");
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);
//...
}
}
這是正確的決定嗎? 還是會更好?
是的它幾乎是正確的..你必須改變的唯一事情是在每個連接上創建NioEventLoopGroup。
NioEventLoopGroup實例很昂貴,因此應該共享它們。 通過每次將相同的實例傳遞給Bootstrap.group(...)來創建一個實例並共享它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.