Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

java - Netty 4 multiple client

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes its almost correct.. The only thing you MUST change is the creation of NioEventLoopGroup on every connect.

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..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...