// private methods private void connect() { IsConnected = false; if (connecting) { return; } if (client != null) { client.Close(); client = null; } try { client = new TcpClient { NoDelay = true, ReceiveBufferSize = 8192, SendBufferSize = 8192 }; client.Connect("irc.chat.twitch.tv", 6667); stream = client.GetStream(); var reader = new StreamReader(stream); var messageQueue = new ConcurrentQueue <IrcMessage>(); var messageQueueAddedEvent = new AutoResetEvent(false); new Thread(() => { try { string line; while ((line = reader.ReadLine()) != null) { #if DEBUG System.Diagnostics.Debug.WriteLine(line); #endif IrcMessage msg; if (IrcMessage.TryParse(line, out msg)) { if (msg.Command == "PING") { WriteLine("PONG"); } else if (msg.Command == "PONG") { receivedPong = true; } messageQueue.Enqueue(msg); messageQueueAddedEvent.Set(); } } } catch { } }).Start(); new Thread(() => { bool inQueue = false; IrcMessage message; while (true) { messageQueueAddedEvent.WaitOne(); while (messageQueue.TryDequeue(out message)) { int count = messageQueue.Count; if (messageQueue.Count > 50) { IrcMessage.TryParse($"@system-msg=ignored\\s{count}\\smessages USERNOTICE #{message.Middle}", out message); IrcMessage nil; for (int i = 0; i < count; i++) { messageQueue.TryDequeue(out nil); } MessageReceived?.Invoke(this, new MessageEventArgs(message)); } else { MessageReceived?.Invoke(this, new MessageEventArgs(message)); } } } }).Start(); if (!string.IsNullOrEmpty(password)) { writeLine(stream, "PASS " + password); } writeLine(stream, "NICK " + username); writeLine(stream, "CAP REQ :twitch.tv/commands"); writeLine(stream, "CAP REQ :twitch.tv/tags"); receivedPong = true; IsConnected = true; Connected?.Invoke(this, EventArgs.Empty); } catch (Exception exc) { ConnectionException?.Invoke(this, new ExceptionEventArgs(exc)); } }
public static bool TryParse(string line, out IrcMessage message) { string tags = null, prefix = null, command = null, middle = null, @params = null; int i = 0, end; // tags if (i >= line.Length) { goto error; } if (line[i] == '@') { i++; end = line.IndexOf(' ', i); if (end == -1) { goto error; } tags = line.Substring(i, end - i); i = end + 1; } // prefix if (i >= line.Length) { goto error; } if (line[i] == ':') { i++; end = line.IndexOf(' ', i); if (end == -1) { goto error; } prefix = line.Substring(i, end - i); i = end + 1; } // command if (i >= line.Length) { goto error; } end = line.IndexOf(' ', i); if (end == -1) { end = line.Length; } if (end == i) { goto error; } command = line.Substring(i, end - i); i = end + 1; // params if (i < line.Length) { if (line[i] != ':') { end = line.IndexOf(' ', i); if (end == -1) { end = line.Length; } middle = line.Substring(i, end - i); i = end + 1; } if (i < line.Length) { if (line[i] == ':') { @params = line.Substring(i + 1); } } } message = new IrcMessage(tags, prefix, command, middle, @params); return(true); error: message = null; return(false); }