/// <summary> /// Asynchronous read has completed. /// </summary> /// <param name="ar">IAsyncResult object.</param> private void ReadComplete(IAsyncResult ar) { try { StateObject stateObject = (StateObject)ar.AsyncState; if (stateObject.Stream.CanRead) { int bytesReceived = stateObject.Stream.EndRead(ar); if (bytesReceived > 0) { messageStream.Write(Encoding.GetString(stateObject.Buffer, 0, bytesReceived)); while (messageStream.DataAvailable) { string message = messageStream.Read(); OnMessageReceived(new IrcMessage(message)); } } else // 0 bytes read, the remote host has shut down the connection. { if (OnConnectionLost != null) { OnConnectionLost(this, EventArgs.Empty); } } } Receive(); } catch (SocketException) { if (OnConnectionLost != null) { OnConnectionLost(this, EventArgs.Empty); } } catch (IOException) { if (OnConnectionLost != null) { OnConnectionLost(this, EventArgs.Empty); } } catch (Exception) { if (OnConnectionLost != null) { OnConnectionLost(this, EventArgs.Empty); } } }