Closing event for socket

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi folks

is it possible to let VB.NET call a specific handler, when a socket gets closed (either as a server, or as a client)

Thank
Helmut
 
I think you're asking how to detect when a socket is closed remoteley. I banged my head against that one for quite a while. It's documented very poorly. If that's what you're looking for, this should help.

This snippet is in C# but you should be able to convert it. There's a lot left out so e-mail me if you have any questions

/// code above here ommitte

//continuously poll for incoming messages on this connectio
while(userIsLogedIn

//wait for the connection's mutex to come fre
con.Mtx.WaitOne()
Debug.WriteLine(" Locked " + con.Name, "CommThread")

//poll the socket for incoming data (1 second timeout
if(con.Sock.Poll(1000, SelectMode.SelectRead)

if(con.Ns.DataAvailable

//read the incoming dat
numBytes = con.Sock.Receive(peekBytes,SocketFlags.Peek)
bytes = new byte[numBytes]
con.Ns.Read(bytes, 0, Convert.ToInt32(bytes.Length))

//throw the event (the event determines what to do with the message
this.OnIncomingMessage(this, new MessageEventArgs(bytes, con))

else //client is probably disconnecting

//test for remote disconnection
byte [] buffer = new byte[1];
if(con.Sock.Receive(buffer, SocketFlags.Peek) <= 0)

//no data recieved: this IS a disconnection so throw the even
this.OnRemoteDisconnection(this, new ConnectionEventArgs(con))

//break out of the loop to cause a full local disconnectio
break



els

noData = true


/// code below here ommitted
 
If you are using synchronous mode then there are no "perfect" solution,
because there are no separate thread where your handler can be called. If
you are using asynchronous sockets (that you probably should) as soon as
socket will be closed "read handler" will be called and EndReceive will
throw exception when you will call it.
 
Back
Top