10
我需要使客戶端能夠建立多個連接。我使用Netty 4.0。不幸的是,所有現有的示例都沒有顯示如何創建大量連接。Netty 4多個客戶端
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);
//...
}
}
這是正確的決定嗎?或者它可能會更好?
和TelnetClientInitializer()怎麼樣,也足以創建一個實例? – user1221483
取決於代碼..它是@Sharable或不);)? –
是的,它是可共享的 – user1221483