Click here to Skip to main content
11,634,568 members (66,374 online)
Click here to Skip to main content

How to detect a connection loss in .Net Sockets

, 17 Mar 2005 61.8K 21
Rate this:
Please Sign up or sign in to vote.
Explains how to detect when a remote peer closes the connection

Introduction

Detecting the closing of a connection is an important part of handling sockets, this article isn't the most complicated one there is, but it clarifies some info that i had to look for in a lot of places.

The problem was (for me :] ) how to detect when a Socket connection is closed by the other peer. and this is all about the solution

Where did i find the solution

i must state that i have looked into it alot and it really made me feel good to get this. As i looked EVERYWHERE in the web for the key as i finaly found it in this newbie FAQ

http://tangentsoft.net/wskfaq/newbie.html

and it is actually pretty simple. (There are lots of other important information in there.)

The Solution

i'll quote the article :

"With asynchronous sockets, Winsock sends you an FD_CLOSE message when the connection drops. Event objects are similar: the system signals the event object with an FD_CLOSE notification.

With blocking and non-blocking sockets, you probably have a loop that calls recv() on that socket. recv() returns 0 when the remote peer closes the connection. As you would expect, if you are using select(), the SOCKET descriptor in the read_fds parameter gets set when the connection drops. As normal, you'll call recv() and see the 0 return value."


I'll supply i small segment of vb.net code just to demostrate
Note: This is for using Synchronous Sockets

Try
  
   Dim ReceivedBytes As Integer
  
   Dim tmpBuffer As Byte()
 
   ReDim tmpBuffer(1024)

 
 
   While blActive And Socket.Connected
 
      ' Resetting received bytes

      tmpBuffer.Clear(tmpBuffer, 0, tmpBuffer.Length)
  
      ' Getting new bytes
  
      ReceivedBytes = Socket.Receive(tmpBuffer, 0, tmpBuffer.Length, Sockets.SocketFlags.None)
 
      ' Note: monitoring the blActive member as socket might have been closed prior the this point

      If ReceivedBytes > 0 And blActive Then
 
           ' Your code here to handle the new data

          DataReceived_Handler(tmpBuffer) ' <- Your handler
  
      Else
   
          ' if returned with 0 bytes, that means the connection is lost
          ' Use your personalized code to handle the closure of the connection
          yourCloseSocket() ' close the connection
    
      End If



   End While


(Fade) NOTE: This only detects when the closing of the connection is notifiable by your peer, in case of an unpredictable disconnection (a router in the middle of nowhere get blown to pieces) both peers might not receive notification on the disconnection, so be sure to send "Keep-Alive" packets (your own - not the ones embedded into the TCP protocol!) to monitor your connection's health.


Some of the knoledge and code presented here originated from my work at ActiveRoom on the Digital Signage system TVM.


Just wanted to share this information,
I'll be sure to post a more comprehensive article about .Net.Sockets, including Async & Sync socket usage and Asynchronous calls when i get the time

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Fade (Amit BS)
Chief Technology Officer ISQ
Israel Israel
Just another coder out there Smile | :)
Currently working on a natural language search index with nanoRep

You may also be interested in...

Comments and Discussions

 
General[Message Deleted] Pin
it.ragester2-Apr-09 21:59
memberit.ragester2-Apr-09 21:59 
GeneralIt's not enough Pin
Eran Aharonovich25-May-06 0:39
memberEran Aharonovich25-May-06 0:39 
GeneralKill Client Process Pin
Vitoto4-May-05 18:26
memberVitoto4-May-05 18:26 
GeneralGood news/Bad news Pin
je_gonzalez17-Oct-04 14:46
memberje_gonzalez17-Oct-04 14:46 
GeneralRe: Good news/Bad news Pin
Jakub Florczyk18-Oct-04 12:17
memberJakub Florczyk18-Oct-04 12:17 
GeneralRe: Good news/Bad news Pin
sfawcett18-Oct-04 15:46
susssfawcett18-Oct-04 15:46 
GeneralRe: Good news/Bad news Pin
Fade (Amit BS)18-Oct-04 23:39
memberFade (Amit BS)18-Oct-04 23:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 17 Mar 2005
Article Copyright 2004 by Fade (Amit BS)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid