如何使用netty 5.0创建大量连接

时间:2016-03-22 09:42:58

标签: java tcp netty nio

我想创建与服务器的大量客户端连接以用于测试目的。我通过每个连接创建线程来实现这一点,所以我只能在我的机器上创建3000连接。下面是我的代码:

.controller('Controller', ['$scope', '$http', '$sce', function($scope, $http, $sce) {

  $http.get('myjson.json').success(function (data){
    $scope.medianew = data.media.map(function (m) {
      m.url = $sce.trustAsResourceUrl(m.url);
      return m;
    });

  }]);

我可以获得更多连接。

我在进行谷歌研究后尝试了另一种解决方案,但频道会自动关闭。

1 个答案:

答案 0 :(得分:0)

这是我的另一个解决方案

package com.stepnetwork.iot.apsclient.application;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sam on 3/22/16.
 */
public class Test {

    private static final String HOST = "192.168.54.36";
    private static final int PORT = 30080;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap(); // (1)
        try {
            bootstrap.group(workerGroup); // (2)
            bootstrap.channel(NioSocketChannel.class); // (3)
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MyClientHandler());
                }
            });


            List<Channel> channels = new ArrayList<>();

            // create many connection here, but the channel will be closed atomically
            for (int i = 0; i < 10000; i++) {
                channels.add(bootstrap.connect(HOST, PORT).sync().channel());
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        while (true) {
            Thread.sleep(Integer.MAX_VALUE);
        }
    }

}