TringBtb
TringBtb
2016-05-16 10:37

怎么用java代码测试serversocket的最大可连接数

不使用JMeter等压力测试软件,怎么使用java代码测试serversocket的最大可连接数?

服务器是利用serversocket,每次接收到一个socket,就提交给线程池,以下是客户端的代码

package Client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
public static void main(String[] args) {
initFile("test.txt");
initFile("time.txt");
ExecutorService pool = Executors.newFixedThreadPool(1000);
for (int i = 0; i < 3000; i++) {
pool.submit(new Thread() {
@Override
public void run() {
sendSocket();
}
});
}
pool.shutdown();
}

public static void initFile(String fileName) {
    File file = new File(fileName);
    if (file.exists())
        file.delete();
}

public static void sendSocket() {
    Socket socket = null;
    try {
        socket = new Socket("127.0.0.1", 14);
        long startTime = System.currentTimeMillis();
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String string = "";
        String line;
        while ((line = reader.readLine()) != null) {
            string += line;
        }
        string += "\r\n";
        long endTime = System.currentTimeMillis();
        FileOutputStream fos = new FileOutputStream("test.txt", true);
        fos.write(string.getBytes());
        fos.flush();
        fos.close();
        fos = new FileOutputStream("time.txt", true);
        String time = (endTime - startTime) + "ms\r\n";
        fos.write(time.getBytes());
        fos.flush();
        fos.close();
    } catch (UnknownHostException e) {
        System.out.println("UnknownHostException");
    } catch (IOException e) {
        System.out.println("IOException1");
    } finally {
        if (socket != null)
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("IOException2");
            }
    }
}

}

发现客户端数量为3000的时候就会打印IOEXCEPTION1,但是服务器那边却没有崩溃。到底该怎么测试最大可连接数呢?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换