private void ReceiveMessage() { if (client == null || !client.Connected || client.Available == 0) { return; } lastReceive = DateTime.UtcNow.Ticks; int bytesToRead = bufferSize - bufferPos; if (bytesToRead > client.Available) { bytesToRead = client.Available; } int bytesRead = client.GetStream().Read(buffer, bufferPos, bytesToRead); bufferPos += bytesRead; if (bufferPos == bufferSize) { if (readingHeader) { using (MessageReader mr = new MessageReader(buffer)) { messageType = (DiscordServerMessageType)mr.Read <int>(); int length = mr.Read <int>(); if (length == 0) { HandleMessage(); bufferPos = 0; bufferSize = 8; readingHeader = true; } else { bufferPos = 0; bufferSize = length; readingHeader = false; return; } } } else { HandleMessage(); bufferPos = 0; bufferSize = 8; readingHeader = true; } } }
private void SendToDLC(DiscordLinkConnection dlc, DiscordServerMessageType type, byte[] data) { dlc.lastSend = DateTime.UtcNow.Ticks; if (!dlc.tcpClient.Connected) { lock (clients) { Console.WriteLine(dlc.linkKey + " disconnected."); clients.Remove(dlc); } return; } if (dlc.linkKey == 0) { return; } try { byte[] sendData; using (MessageWriter mw = new MessageWriter()) { mw.Write <int>((int)type); if (data == null || data.Length == 0) { mw.Write <int>(0); } else { mw.Write <byte[]>(data); } sendData = mw.GetMessageBytes(); } dlc.tcpClient.GetStream().Write(sendData, 0, sendData.Length); } catch { if (type != DiscordServerMessageType.DISCONNECT) { Console.WriteLine("Error sending, disconnecting " + dlc.linkKey); SendDisconnect(dlc); } } }