java – Netty 4多客户端

我需要使客户端能够进行很多连接.我使用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(…).

相关文章

前言 池化思想在实际开发中有很多应用,指的是针对一些创建成...
Netty实现httpserver简单示例 3个Java类实现最基本的接收请求...
Java NIO系列1 概观 Java NIO。中间的N你既可以理解为(new)...
关键字:使用Netty实现HTTP服务器,使用Netty实现httpserver...
netty心跳机制示例,使用Netty实现心跳机制,使用netty4,Id...
关键字:Netty开发redis客户端,Netty发送redis命令,netty解...