【问题标题】:Netty 4 multiple clientNetty 4 多客户端
【发布时间】:2012-10-20 13:51:20
【问题描述】:

我需要让客户端能够建立许多连接。我使用 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);
    //...
    }
}

这是正确的决定吗?还是会更好?

【问题讨论】:

    标签: java client netty connection


    【解决方案1】:

    是的,它几乎是正确的。您唯一必须更改的是在每次连接时创建 NioEventLoopGroup。

    NioEventLoopGroup 实例很昂贵,因此应该共享它们。创建一个实例并共享它,每次都将同一个实例传递给 Bootstrap.group(...)..

    【讨论】:

    猜你喜欢
    • 2014-10-07
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多