[英]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.