tags:

views:

20

answers:

2

I'm implementing a java TCP/IP Server using ServerSocket to accept messages from clients via network sockets.

Works fine, except for clients on PDAs (a WIFI barcode scanner). If I have a connection between server and pda - and the pda goues into suspend (standby) after some idle time - then there will be problems with the connection. When the pda wakes up again, I can observer in a tcp monitor, that a second connection with a different port is established, but the old one remains established too:

localhost:2000 remotehost:4899 ESTABLISHED (first connection)

localhost:2000 remotehost:4890 ESTABLISHED (connection after wakeup)

And now communication doesn't work, as the client now uses the new connection, but the server still listens at the old one - so the server doesn't receive the messages. But when the server sends a message to the client he realizes the problem (receives a SocketException: Connection reset. The server then uses the new connection and all the messages which have been send in the meantime by the client will be received at a single blow!

So I first realize the network problems, when the server tries to send a message - but in the meantime there are no exceptions or anything. How can I properly react to this problem - so that the new connection is used, as soon as it is established (and the old one closed)?

+1  A: 

It sounds like the major issue is that you want the server to realize and drop the old connections as they become stale.

Have you considered setting a timeout on the connection on the server-side socket (the connection Socket, not the ServerSocket) so you can close/drop it after a certain period? Perhaps after the SO_TIMEOUT expires on the Socket, you could test it with an echo/keepalive command to verify that the connection is still good.

Ophidian
+1  A: 

From your description I guess that the server is structured like this:

server_loop
{
    client_socket = server_socket.accept()
    TalkToClientUntilConnectionCloses(client_socket)
}

I'd change it to process incoming connections and established connections in parallel. The simplest approach (from the implementation point of view) is to start a new thread for each client. It is not a good approach in general (it has poor scalability), but if you don't expect a lot of clients and can afford it, just change the server like this:

server_loop
{
    client_socket = server_socket.accept()
    StartClientThread(client_socket)
}

As a bonus, you get an ability to handle multiple clients simultaneously (and all the troubles attached too).

atzz
thx, that solved my problem!
räph