Pregunta

situation:- client1: user side application where they connect to server with username. The connection is to stay alive with client1 waiting for messages from server.

client2: event fired application that asks server for all the users connected and closes its connection. It will process the users list and select one user. It will connect back to the server and ask it to send a message to the selected user.

Server: listen for client1 on 11111 and client2 on 22222. Connection with client1 is to be kept alive until user logs out in client1 software. client2 demands list, selects an element, asks server to relay message to that instance of client1. If client1 is down by that time, server responds with false and client2 goes back to step of getting list of live instances of client1.

Problem I am facing:- How to implement a system in client1 so that it connects to server when user actions connect UI element, and then it keeps the connection live at all times, in case the connection goes down, it reconnects on its own. Simultaneously it should poll the inputstream to receive any messages that server might send while it is connected.

Precisely, I am facing a problem accessing the same single socket instance by 2 threads, one to keep connection alive and reconnect if went down, and another to keep looking for data in inputstream. If the KeepAlive thread checks connection and at the same time MessageReader thread would be receive data, then the system would crash.

¿Fue útil?

Solución

What I usually do is use a read timeout on the client to initiate a server poll, then go back to reading. If another read timeout occurs, the client knows that its server is unreachable, closes its socket and falls back to attempting to re-open the connection every, say, 10 seconds. Pseudo-C:

boolean pollOustanding;

while true{
  if connectAttempt(){
    pollOutstanding:=false;
    while(true){
       if readWithTimeout(2000){
          handleReceivedData(); // could be 'real' data, or poll reply from server
          pollOutstanding:=false;
       }
       else
         { if (pollOutstanding) break;
           pollOutstanding=true;
           sendPoll();
         };
    };
    closeSocket;
  };
  Sleep(10000);
};

Only needs one thread - you don't need to poll the sever if data is being received - the connection must be OK.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top