views:

329

answers:

4

I run my application on a network and in some cases the client lost connection to the server. After this time, when I wanted to send a message to the server I receive the following error: Operation not allowed on non-connected sockets (something like this).

I thought to create an event for object type TcpClient and when tcp_obj.Connected = false to call a function to discontinue execution of the current code. How could I do this?

Or giving me other suggestios.

Thanks.

A: 

I know at least from socket programming in Java that when a client loses connection to the server, the server does not and can not know about it. You need a heartbeat of some sort to detect the early disconnection.

We often use a heartbeat in our client/server applications to detect early disconnections and log them on the server. This way the server can close the associated socket and release the connection back to the pool.

Simply send a command to the client periodically and wait for a response. If no response is garnered within a timeout assume disconnect and close streams.

Chris Kannon
A: 

I would simply first check your connection object to ensure you are connected, prior to attempting to send the message. Also make sure that you are putting your send-logic inside of a try-catch, so that if you do happen to get disconnected mid transmission, you'll be able to resume without blowing your application apart.

Psuedo-Code:

private void SendMessage(string message, Socket socket)
{
  if(socket.connectionState = States.Connected)
  {
      try{
        // Attempt to Send
      }
      catch(SocketException Ex)
      {
        // Disconenct, Additional Cleanup Etc.
      } 
}
}

If you are in C#, prior to your connection state changing, you will have a socket disconnected event fire, prior to your connection state changing. Make sure you tie this event up as soon as your socket connects.

George
How can I create a TCP disconnected event fire? Can you give me an example?
Emanuel
A: 

Hi there,

Can we know why you use TCP sockets? Is for calling a tcp device o server code?

I recommend you if is for calling a .net server app use Windows Communication Foudation. It is simple to expose services by net.tcp, http, etc.

Regards,

Arturo Caballero
A: 

Actually this is a very old problem,

If I understand your question correctly you need a way to know whether you're application is still connected to the server or vice versa.

If so then a workaround is to have a UDP connection just to check the connectivity (overhead I know, but its much better then polling on Connected state), you could check just before you send you're data.

Since UDP is not Connection oriented you don't need to be connected when you send the data

Vivek Bernard