private void StreamReceiver(IAsyncResult ar) { int bytesRead; try { if (fIsConnected) { bytesRead = fConnection.EndReceive(ar); if (bytesRead > 0) { fBytesIn += bytesRead; fMyListener.fBytesIn += bytesRead; fLastDataAction = DateTime.Now.Ticks; switch (fUseMessageCollector) { case true: fLastMessageCollectorPacket = new MessageCollectorTCPClientConnectionPacket(this, Encoding.Default.GetString(fReadBuffer, 0, bytesRead), fLastMessageCollectorPacket); break; case false: fLastIncomingPacket = new IncomingTCPClientConnectionPacket(this, new DataFrame(fReadBuffer, 0, bytesRead), fLastIncomingPacket); break; } } else { DisconnectMe(); return; } //Start a new asynchronous read into readBuffer. fConnection.BeginReceive(fReadBuffer, 0, fReadBufferSize, SocketFlags.None, new AsyncCallback(StreamReceiver), null); } } catch (ArgumentNullException argumentNullException) //asyncResult is a null reference (Nothing in Visual Basic). { DisconnectMe(); } catch (ArgumentException argumentException) //asyncResult was not returned by a call to the BeginReceive method. { DisconnectMe(); } catch (SocketException socketException) //An error occurred when attempting to access the socket. See the Remarks section for more information { DisconnectMe(); } catch (ObjectDisposedException objectDisposedException) //Socket has been closed. { DisconnectMe(); } catch (Exception ex) { fConnection.BeginReceive(fReadBuffer, 0, fReadBufferSize, SocketFlags.None, new AsyncCallback(StreamReceiver), null); } }
public void DisconnectMe() { if (fActive) { fActive = false; fIsConnected = false; try { fConnection.Close(); } catch (Exception ex) { } if (fUseMessageCollector && fMyMessageCollector != null) { fMyMessageCollector.Dispose(); } if (fLastIncomingPacket != null) { fLastIncomingPacket.Cancel(); } if (fLastOugoingPacket != null) { fLastOugoingPacket.Cancel(); } if (fLastMessageCollectorPacket != null) { fLastMessageCollectorPacket.Cancel(); } fConnection = null; fLastIncomingPacket = null; fLastOugoingPacket = null; fLastMessageCollectorPacket = null; fMyMessageCollector = null; fMyListener.RemoveClient(fIPAddress); fMyListener.MyExtasysTCPServer.OnClientDisconnect(this); } }