Click here to Skip to main content
15,895,709 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Dear readers,

I have a windows service (client) which basically should be up 24/7, however sometimes the connection drops.
Basically what happens is that i send a command to the service, and i will get the response "An existing connection was forcibly closed by the remote host".

Now what i would expect is that the IsConnected function (called from timer) notices that the connection has dropped and restarts the connection but it doesn't actually notice that the connection has closed.

C#
private bool IsConnected(Socket socket)
{
    try
    {
        return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
    }
    catch (SocketException) { return false; }
}


But it doesn't seem to work..
Another idea was to actually send data as a keep alive, but if the timer event raises while for example the socket is in the middle of transferring a file it goes to hell.

Socket:
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

     IPEndPoint ipEnd = new IPEndPoint(IPAddress.Loopback, 1500);

     clientSocket.Connect(ipEnd);


Any suggestions are very welcome,

Thanks!
Posted
Updated 2-Jun-11 1:23am
v4
Comments
Mathew Crothers 1-Jun-11 22:44pm    
Do you mean that the socket on the service fails, or that clients connected to the service drop their connections?
Ankit Rajput 2-Jun-11 0:36am    
Your problem is not clear. If you are getting any exception then please update your question with Exception.

1 solution

Hi Scalee,

Your First approach is correct one, try with this

private bool IsConnected(Socket socket)
{
    try
    {
        if(socket.Connected)
          return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
        else
          return false; 
    }
    catch (SocketException) { return false; }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900