[英]Java TCP Server doesn't accept client request after receiving 16384 bytes MAC OS
I'm conducting an experiment to see how long it takes the TCP in java. 我正在进行一项实验,以了解Java中TCP需要花费多长时间。 First I start the server.
首先,我启动服务器。 Then call the function client_tcp many times, more than 50000 times.
然后,多次调用函数client_tcp,超过50000次。 And measure the time it takes to connect, and send and receive 1 byte.
并测量连接,发送和接收1个字节所需的时间。 When the server get more than 16384 requests (sometimes varies), the client can't connect to the server.
当服务器收到超过16384个请求(有时会有所不同)时,客户端将无法连接到服务器。
I don't know if it is because of the receive buffer size in the server socket. 我不知道是否是因为服务器套接字中的接收缓冲区大小。 In my case, ss.getReceiveBufferSize() = 131072.
就我而言,ss.getReceiveBufferSize()= 131072。
Here is the code: 这是代码:
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;
}
}
What's wrong? 怎么了?
Thank you. 谢谢。
You are creating a massive number of sockets almost at once and the OS is not having time enough to release them. 您几乎一次创建了大量套接字,而操作系统没有足够的时间来释放它们。 You could add a tiny delay (to be experimentally tuned) to the loop that invokes the
client_tcp()
method. 您可以在调用
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.