我的TCP服务器
public static void main(String argv[]) throws Exception {
ServerSocket server = new ServerSocket(3333);
System.out.println("Server started");
while (true) {
Socket socket = server.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Received: " + input.readLine() + "\n");
}
}
我的TCP客户端。
public static void main(String[] args) throws IOException {
for (int i = 1; i < 50000; i++) {
Socket clientSocket = new Socket("localhost", 3333);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(i + "\n");
clientSocket.close();
System.out.println(i);
}
}
TCP客户端中的循环运行到16374并停止,抛出此异常。
...
...
...
16372
16373
16374
Exception in thread "main" java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at mawia.test.Client.main(Test.java:11)
答案 0 :(得分:2)
Fildor是对的,你创建了太多的连接或Socket handles
,这内部转换为每个进程允许open-file-handles
,这很可能是你破坏了。
理想的方法是让客户端继续在一个连接上发送数据(50000 records
),即Socket
和Server
应该处理在单独的线程中处理这些数据(所以你可以运行多个TCP客户端并发):
TCP服务器
public static void main(String argv[]) throws Exception {
ServerSocket server = new ServerSocket(3333);
System.out.println("Server started");
while (true) {
final Socket socket = server.accept();
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("Server received message from client: ");
BufferedReader input;
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(!socket.isClosed() && socket.getInputStream().available() > 0){
System.out.println("Received: " + input.readLine() + "\n");
}
System.out.println("Client disconnected from server");
} catch (IOException e) {
//break;
}
}
});
t.start();
}
}
TCP客户端
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket("localhost", 3333);
for (int i = 1; i < 50000; i++) {
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(i + "\n");
outToServer.flush();
System.out.println(i);
}
clientSocket.close();
}
答案 1 :(得分:0)
在关闭连接之前,请先尝试在TCP客户端代码中添加flush()
,然后与我合作。