繁体   English   中英

接收到16384个字节的MAC OS后,Java TCP Server不接受客户端请求

[英]Java TCP Server doesn't accept client request after receiving 16384 bytes MAC OS

我正在进行一项实验,以了解Java中TCP需要花费多长时间。 首先,我启动服务器。 然后,多次调用函数client_tcp,超过50000次。 并测量连接,发送和接收1个字节所需的时间。 当服务器收到超过16384个请求(有时会有所不同)时,客户端将无法连接到服务器。

我不知道是否是因为服务器套接字中的接收缓冲区大小。 就我而言,ss.getReceiveBufferSize()= 131072。

这是代码:

public synchronized void server_tcp(int port) {
    ServerSocket ss;
    Socket       so;
    InputStream  is;
    OutputStream os;

    try {           
        ss = new ServerSocket(port);
    } catch (Exception e) {
        System.out.println("Unable to connect to port " + port +
                " TCP socket.");
        return;
    }

    while (true) {
        try {
            so = ss.accept();
            is = so.getInputStream();
            os = so.getOutputStream();
            int ch = is.read();
            os.write(65);
            so.close();
        } catch (IOException e) {
            System.out.println("Something went wrong.");
        } catch (InterruptedException e) {
            System.out.println("Bye.");
        }
    }
}

public void client_tcp(String host, int port) {

    Socket       so = null;
    InputStream  is = null;
    OutputStream os = null;

    try {
        so = new Socket(host, port);
    } catch (UnknownHostException e) {
        System.err.println("Error Host not found.");
        return;
    } catch (IOException e) {
        Syste.err.println("Error Creating socket.");
        return;
    }

    try {
        os = so.getOutputStream();
        is = so.getInputStream();

        os.write(65);

        is.read();

        os.close();
        is.close();
        so.close();
    } catch (IOException e) {
        System.err.println("Error.");
        return;
    }
}

怎么了?

谢谢。

您几乎一次创建了大量套接字,而操作系统没有足够的时间来释放它们。 您可以在调用client_tcp()方法的循环中添加一个微小的延迟(以进行实验调整)。

for(int i=0; i<50000; i++) {
    new SocketReuse().client_tcp("127.0.0.1", 4444);
    Thread.sleep(2); // 2 milliseconds delay
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM