sockets Java TCP服务器在收到16384字节的MAC OS后不接受客户端请求
我正在做一个实验,看看java中的TCP需要多长时间。首先我启动服务器。然后多次调用函数client_tcp,超过50000次。测量连接所需的时间,发送和接收1字节。当服务器收到超过16384个请求(有时会有所不同)时,客户端无法连接到服务器
我不知道这是否是因为服务器socket中的接收缓冲区大小。就我而言,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;
}
}
怎么了
谢谢
# 1 楼答案
你几乎同时创建了大量的套接字,而操作系统没有足够的时间来释放它们。您可以向调用
client_tcp()
方法的循环添加一个微小的延迟(通过实验进行调整)