我有一些基本的java套接字客户端/服务器代码,用于在循环中从客户端向服务器发送大量对象:
服务器
final ServerSocket listener = new ServerSocket(8080);
while (true) {
final Socket socket = listener.accept();
try {
final ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
final Object object = ois.readObject();
ois.close();
socket.close();
} catch (Exception e) {
throw new RuntimeException("error", e);
}
}
客户端
public void go() {
try {
while (true) {
sendObject();
}
} catch (Exception e) {
throw new RuntimeException("error", e);
}
}
private void sendObject() throws IOException {
final Socket socket = new Socket("localhost", 8080);
final ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(result);
out.close();
socket.close();
}
这样可以正常工作,直到发送了大约16,000个对象。然后代码最终会超时:
Caused by: java.net.ConnectException: Operation timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at uk.co.imrichardcole.socket.ObjectSocketClientBenchmark.sendObject(ObjectSocketClientBenchmark.java:39)
我认为我没有通过适当的清理来度过一些事情,但尽管尝试了close
和flush
的各种组合,我似乎无法发现它是什么
答案 0 :(得分:3)
您正在通过太多快速连接来填充积压队列。当发生这种情况时,Linux将不会响应进一步的传入连接请求(SYN数据包)。
您应该尽可能长时间使用相同的连接,并且同样的对象也会流。