I have had ServerSockets listening for many months, with hundreds of connections per
second, not a single problem.
Probably out of file descriptors?
For a more robust serversocket listener:
1. ensure all connections are properly closed, no matter what
2. prevent a flood-attack from bringing down your server (lack of file descriptors will crash other processes too)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| final Semaphore preventFlooding = new Semaphore(maxConcurrentConnections);
while(true) { preventFlooding.acquireUninterruptibly(); final Socket socket; try { socket = server.accept(); } catch(IOException exc) { preventFlooding.release(); continue; }
Runnable task = new Runnable() { public void run() { InputStream input = null; OutputStream output = null; try { socket.setSoTimeout(2000); input = socket.getInputStream(); output = socket.getOutputStream();
DO_A_LOT_OF_WORK(socket, input, output); } finally { preventFlooding.release();
try { if(input!=null) input.close(); } catch(IOException exc) { } try { if(output!=null) output.close(); } catch(IOException exc) { } try { socket.close(); } catch(IOException exc) { } } } }
new Thread(task).start(); } |
Regarding the flood attack: I got hit by this so many times that it's silly. Thousands of connections in a few seconds, and if you're not careful, something breaks. Either VM heap, RAM (swapping), threads, running out of file descriptors... that is a serious issue for a server, as every process relies on them. Avoid IOException("Too many files open") at all cost, and my Semaphore will cap your file-descriptor count pretty well.