public void QueueMessage(string message) { QueueMessage(IrcMessage.Parse(message)); }
private void SocketLoop() { Stream stream = null; if (_proxy != null && !string.IsNullOrEmpty(_proxy.ProxyHostname)) { var proxy = new SocksTcpClient(_proxy); var ar = proxy.BeginConnect(_server, _port, null, null); if (WaitHandle.WaitAny(new[] { ar.AsyncWaitHandle, _endWaitHandle }) == 1) { return; } _tcpClient = proxy.EndConnect(ar); } else { _tcpClient = new TcpClient(); var ar = _tcpClient.BeginConnect(_server, _port, null, null); if (WaitHandle.WaitAny(new[] { ar.AsyncWaitHandle, _endWaitHandle }) == 1) { return; } _tcpClient.EndConnect(ar); } stream = _tcpClient.GetStream(); if (_isSecure) { var sslStream = new SslStream(stream, true, (sender, cert, chain, sslPolicyErrors) => { // Just accept all server certs for now; we'll take advantage of the encryption // but not the authentication unless users ask for it. return(true); }); sslStream.AuthenticateAsClient(_server); stream = sslStream; } this.Dispatch(this.OnConnected); byte[] readBuffer = new byte[512], writeBuffer = new byte[Encoding.UTF8.GetMaxByteCount(512)]; int count = 0; bool gotCR = false; var input = new List <byte>(512); IrcMessage outgoing = null; IAsyncResult arr = null, arw = null; while (_tcpClient.Connected) { if (arr == null) { arr = stream.BeginRead(readBuffer, 0, 512, null, null); } _writeWaitHandle.Reset(); if (arw == null && _writeQueue.TryDequeue(out outgoing)) { string output = outgoing.ToString(); count = Encoding.UTF8.GetBytes(output, 0, output.Length, writeBuffer, 0); count = Math.Min(510, count); writeBuffer[count] = 0xd; writeBuffer[count + 1] = 0xa; arw = stream.BeginWrite(writeBuffer, 0, count + 2, null, null); } int idx = WaitHandle.WaitAny( new[] { arr.AsyncWaitHandle, arw != null ? arw.AsyncWaitHandle : _writeWaitHandle, _endWaitHandle }, HeartbeatInterval); switch (idx) { case 0: count = stream.EndRead(arr); arr = null; if (count == 0) { _tcpClient.Close(); } else { for (int i = 0; i < count; i++) { switch (readBuffer[i]) { case 0xa: if (gotCR) { var incoming = IrcMessage.Parse(Encoding.UTF8.GetString(input.ToArray())); this.Dispatch(this.OnMessageReceived, incoming); input.Clear(); } break; case 0xd: break; default: input.Add(readBuffer[i]); break; } gotCR = readBuffer[i] == 0xd; } } break; case 1: if (arw != null) { stream.EndWrite(arw); arw = null; this.Dispatch(this.OnMessageSent, outgoing); } break; case 2: if (arw != null) { stream.EndWrite(arw); } return; case WaitHandle.WaitTimeout: this.Dispatch(this.OnHeartbeat); break; } } this.Dispatch(this.OnDisconnected); }