最大套接字连接可用

时间:2015-10-13 07:25:23

标签: java sockets network-programming

我正在尝试插座编程。我构建了一个简单的echo服务器,它在屏幕上打印客户端文本并向客户端发回一条感谢信息。但是,当我运行客户端(它在一个循环中单独产生10000个请求)时,有时我得到"连接被拒绝"某些客户端线程中的异常。有时候一切都没有任何例外。

以下是我的服务器代码:

public class WebServer {
    static int hitCount = 0;

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(7777, 10000);
        while (true) {
            Socket defaultSocket = serverSocket.accept();
            new Thread(new ServerSlave(defaultSocket)).start();
            System.out.println("Size is :" + hitCount);
        }

    }
}

class ServerSlave implements Runnable {
    Socket clientSocket;

    public ServerSlave(Socket socket) {
        clientSocket = socket;
        WebServer.hitCount++;
    }

    public void run() {

        try {

            DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
            DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
            System.out.println(inputStream.readUTF());
            outputStream.writeUTF("Thank you for contacting the web server");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

以下是我的客户代码:

public class Client {
    static int excepCount=0;
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10000; i++) {
            new Thread(new Worker("" + i)).start();
        }
        Thread.sleep(10000);
        System.out.println( Client.excepCount);
    }
}


class Worker implements Runnable {
    String clientName;

    public Worker(String name) {
        clientName = name;
    }

    public void run() {
        System.out.println("Process started for : " + clientName);
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 7777);
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
            outputStream.writeUTF("Hello socket. Client number " + clientName + "here");
            InputStream inFromServer = socket.getInputStream();
            DataInputStream in =
                    new DataInputStream(inFromServer);
            System.out.println("Server says " + in.readUTF());
            System.out.println("Closing socket");

        } catch (IOException e) {
            Client.excepCount++;
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

不确定我可能做错了什么。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

你期待太多了。客户端以最大速度形成10,000个连接是不现实的。您忘记了TIME_WAIT状态,以及只有64k减去几十个客户端端口的事实。这不是一个现实的测试。如果要对服务器进行负载测试,则需要相当多的客户端主机,或者连接之间的间隔时间更长。