// ============== Setup ================ public Server(ushort Port, ushort maxConnections = 64) { rawServer = new RawServer(Port, maxConnections); rawServer.OnConnect += InternalOnConnect; rawServer.OnDisconnect += InternalOnDisconnect; rawServer.OnPacket += ProcessData; Handlers = new List <Handler>(100); }
// ============= Recv ============== static void ReceiveLoop(Connection connection, RawServer server) { NetworkStream stream = connection.client.GetStream(); DateTime messageQueueLastWarning = DateTime.Now; try { server.OnConnect?.Invoke(connection); while (true) { if (header == null) { header = new byte[4]; } if (!stream.ReadExactly(header, 4)) { break; } int size = Utilities.BytesToIntBigEndian(header); if (size > MaxPacketSize) { Log.WriteNow("ReadMessageBlocking: possible allocation attack with a header of: " + size + " bytes."); break; } byte[] data = new byte[size]; if (!stream.ReadExactly(data, size)) { break; } #if SLEEPY_STATS server.stats.RecvBytesTotal += (ulong)data.Length; server.stats.RecvTotal++; #endif server.OnPacket(connection, data, data.Length); // try // { // server.OnPacket(connection, data, data.Length); // } //#if SLEEPY_DEBUG // catch (Exception e) // { // Log.WriteNow($"Error: On Packet. Likely a callback had an error in it. -> {e.Message}\nStack: {e.StackTrace}"); //#else // catch // { //#endif // } } } catch (Exception exception) { Log.WriteNow("ReceiveLoop: finished receive function for connectionId=" + connection.ID + " reason: " + exception); } finally { stream.Close(); connection.client.Close(); server.OnDisconnect?.Invoke(connection); } }