public static void ServerLoop() { Library.Initialize(); server = new NetworkingSockets(); Address address = new Address(); NetworkingUtils utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Important, (type, message) => { Console.WriteLine("Valve Debug - Type: {0}, Message: {1}", type, message); }); unsafe { int sendRateMin = 5 * 1024 * 1024; int sendRateMax = MAX_UPLOAD; int sendBufferSize = MAX_BUFFER; utils.SetConfigurationValue(ConfigurationValue.SendRateMin, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Int32, new IntPtr(&sendRateMin)); utils.SetConfigurationValue(ConfigurationValue.SendRateMax, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Int32, new IntPtr(&sendRateMax)); utils.SetConfigurationValue(ConfigurationValue.SendBufferSize, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Int32, new IntPtr(&sendBufferSize)); } address.SetAddress("::0", port); uint listenSocket = server.CreateListenSocket(ref address); uint pollGroup = server.CreatePollGroup(); Console.WriteLine($"Server {SERVER_NAME} started Listening on port {port} for maximum of {MAX_PLAYERS} players\nEnforcing maps is {ENFORCE_MAPS}"); StartAnnouncing(); StatusCallback status = (ref StatusInfo info, IntPtr context) => { switch (info.connectionInfo.state) { case ConnectionState.None: break; case ConnectionState.Connecting: server.AcceptConnection(info.connection); server.SetConnectionPollGroup(pollGroup, info.connection); break; case ConnectionState.Connected: Console.WriteLine("Client connected - IP: " + info.connectionInfo.address.GetIP()); bool openSlot = false; for (byte i = 0; i < MAX_PLAYERS; i++) { if (players[i] == null) { players[i] = new Player(i, info.connection, info.connectionInfo.address); byte[] versionNumber = ASCIIEncoding.ASCII.GetBytes(VERSION_NUMBER); byte[] versionMessage = new byte[versionNumber.Length + 1]; versionMessage[0] = (byte)OpCode.VersionNumber; Array.Copy(versionNumber, 0, versionMessage, 1, versionNumber.Length); server.SendMessageToConnection(players[i].connection, versionMessage, SendFlags.Reliable | SendFlags.NoNagle); if (ENFORCE_MAPS) { server.SendMessageToConnection(players[i].connection, mapListBytes, SendFlags.Reliable); server.SendMessageToConnection(players[i].connection, GetCurrentMapHashMessage(), SendFlags.Reliable); } foreach (Player player in players) { if (player != null && player != players[i]) { server.SendMessageToConnection(players[i].connection, new byte[] { (byte)OpCode.Connect, player.playerID }, SendFlags.Reliable); server.SendMessageToConnection(player.connection, new byte[] { (byte)OpCode.Connect, i }, SendFlags.Reliable); if (player.usernameMessage != null) { server.SendMessageToConnection(players[i].connection, player.usernameMessage, SendFlags.Reliable); } if (player.allGearUploaded) { foreach (KeyValuePair <string, byte[]> value in player.gear) { server.SendMessageToConnection(players[i].connection, value.Value, SendFlags.Reliable); } } } } server.FlushMessagesOnConnection(players[i].connection); openSlot = true; break; } } if (!openSlot) { server.CloseConnection(info.connection); } break; case ConnectionState.ClosedByPeer: RemovePlayer(info.connection); break; } }; #if VALVESOCKETS_SPAN MessageCallback messageCallback = (in NetworkingMessage netMessage) => { byte[] messageData = new byte[netMessage.length]; netMessage.CopyTo(messageData); Player sendingPlayer = null; foreach (Player player in players) { if (player != null && player.connection == netMessage.connection) { sendingPlayer = player; break; } } if (sendingPlayer != null) { ProcessMessage(messageData, sendingPlayer.playerID, server); } }; #else const int maxMessages = 256; NetworkingMessage[] netMessages = new NetworkingMessage[maxMessages]; #endif while (RUNNING) { server.DispatchCallback(status); #if VALVESOCKETS_SPAN server.ReceiveMessagesOnPollGroup(pollGroup, messageCallback, 256); #else int netMessagesCount = server.ReceiveMessagesOnConnection(listenSocket, netMessages, maxMessages); if (netMessagesCount > 0) { for (int i = 0; i < netMessagesCount; i++) { ref NetworkingMessage netMessage = ref netMessages[i]; byte[] messageData = new byte[netMessage.length]; netMessage.CopyTo(messageData); Player sendingPlayer = null; foreach (Player player in players) { if (player != null && player.connection == netMessage.connection) { sendingPlayer = player; break; } } //Console.WriteLine("Recieved packet from connection {0}, sending player null: {1}", netMessage.connection, sendingPlayer == null); if (sendingPlayer != null) { ProcessMessage(messageData, sendingPlayer.playerID, server); } netMessage.Destroy(); } } #endif mapVotes.Clear(); total_players = 0; foreach (Player player in players) { if (player != null) { total_players++; if (player.timeoutWatch.ElapsedMilliseconds > 15000) { Console.WriteLine($"{player.playerID} has been timed out for not responding for 15 seconds"); RemovePlayer(player.connection, player.playerID, true); } if (!mapVotes.ContainsKey(player.currentVote)) { mapVotes.Add(player.currentVote, 1); } else { mapVotes[player.currentVote]++; } } } // Handle map voting and map enforcement if (ENFORCE_MAPS) { if (total_players == 0) { currentMapHash = "1"; } bool startNewTimer = false; if (mapVotes.ContainsKey("current")) { if (mapVotes["current"] < (int)Math.Ceiling((float)total_players / 2)) { if (!mapVoteTimer.IsRunning) { startNewTimer = true; } } } else if (!mapVoteTimer.IsRunning && total_players > 0) { startNewTimer = true; } if (startNewTimer) { mapVoteTimer.Restart(); byte[] mapVoteMsg = new byte[] { (byte)OpCode.MapVote, 0, 0 }; foreach (Player player in players) { if (player != null) { server.SendMessageToConnection(player.connection, mapVoteMsg, SendFlags.Reliable); } } } if (mapVoteTimer.IsRunning && mapVoteTimer.ElapsedMilliseconds > 30000 && total_players > 0) { mapVoteTimer.Stop(); Tuple <string, int> mostVoted = null; foreach (var item in mapVotes) { if (!item.Key.Equals("current")) { if (mostVoted == null || mostVoted.Item2 < item.Value) { mostVoted = Tuple.Create <string, int>(item.Key, item.Value); } } } currentMapHash = mostVoted.Item1; byte[] newMapMessage = GetCurrentMapHashMessage(); foreach (Player player in players) { if (player != null) { server.SendMessageToConnection(player.connection, newMapMessage, SendFlags.Reliable); player.currentVote = "current"; } } } else if (total_players == 0) { mapVoteTimer.Stop(); } } }
private static void ProcessMessage(byte[] buffer, byte fromID, NetworkingSockets server) { if (!Enum.IsDefined(typeof(OpCode), (OpCode)buffer[0]) || players[fromID] == null) { return; } players[fromID].timeoutWatch.Restart(); switch ((OpCode)buffer[0]) { case OpCode.Settings: Thread usernameThread = new Thread(new ParameterizedThreadStart(Server.HandleUsername)); usernameThread.IsBackground = true; usernameThread.Start(Tuple.Create(buffer, fromID)); break; case OpCode.Texture: { Console.WriteLine("Received Texture from " + fromID); Player player = players[fromID]; if (player != null && player.playerID == fromID) { player.AddGear(buffer); if (player.allGearUploaded) { foreach (Player player2 in players) { if (player2 != null && player2.playerID != fromID) { foreach (KeyValuePair <string, byte[]> value in player.gear) { server.SendMessageToConnection(player2.connection, value.Value, SendFlags.Reliable); } server.FlushMessagesOnConnection(player2.connection); } } } } } break; case OpCode.Animation: if (players[fromID] != null) { bool reliable = buffer[buffer.Length - 1] == (byte)1 ? true : false; buffer[buffer.Length - 1] = fromID; foreach (Player player in players) { if (player != null && player.playerID != fromID) { ConnectionStatus status = new ConnectionStatus(); if (server.GetQuickConnectionStatus(player.connection, ref status)) { int bytesPending = status.pendingReliable + status.sentUnackedReliable; if (reliable && bytesPending >= MAX_BYTES_PENDING) { Console.WriteLine($"Sending animation unreliably to ({player.playerID}) because pending bytes is higher than max"); reliable = false; } } server.SendMessageToConnection(player.connection, buffer, reliable ? SendFlags.Reliable | SendFlags.NoNagle : SendFlags.Unreliable | SendFlags.NoNagle); } } } break; case OpCode.Chat: string contents = ASCIIEncoding.ASCII.GetString(buffer, 1, buffer.Length - 1); Console.WriteLine("Chat Message from {0} saying: {1}", fromID, contents); byte[] sendBuffer = new byte[buffer.Length + 1]; Array.Copy(buffer, 0, sendBuffer, 0, buffer.Length); sendBuffer[buffer.Length] = fromID; foreach (Player player in players) { if (player != null) { server.SendMessageToConnection(player.connection, sendBuffer, SendFlags.Reliable); } } break; case OpCode.MapVote: if (ENFORCE_MAPS) { string vote = ASCIIEncoding.ASCII.GetString(buffer, 1, buffer.Length - 1); if (mapList.ContainsKey(vote) || vote.ToLower().Equals("current")) { vote = mapList.ContainsKey(vote) && mapList[vote].Equals(currentMapHash) ? "current" : vote; players[fromID].currentVote = vote; Console.WriteLine("{0} voted for the map {1}", fromID, mapList.ContainsKey(vote) ? mapList[vote] : vote); } } break; case OpCode.StillAlive: if (players[fromID] != null) { server.SendMessageToConnection(players[fromID].connection, buffer, SendFlags.Unreliable | SendFlags.NoNagle); } break; } }