public override void OnEndGame(EndGameMessage msg) { base.OnEndGame(msg); var scene = GameObject.Find("GameScene").GetComponent <GameScene>(); scene.OpenPopup <PopupOneButton>("PopupOneButton", popup => { if (msg.winnerPlayerIndex == playerInfo.netId) { popup.gameObject.GetComponent <SortingGroup>().sortingLayerName = "HandCards"; popup.gameObject.GetComponent <SortingGroup>().sortingOrder = 2500; popup.text.text = "You win!"; } else { popup.gameObject.GetComponent <SortingGroup>().sortingLayerName = "BoardCards"; popup.gameObject.GetComponent <SortingGroup>().sortingOrder = 2500; popup.text.text = "You lose!"; } popup.buttonText.text = "Exit"; popup.button.onClickEvent.AddListener(() => { if (NetworkingUtils.GetLocalPlayer().isServer) { NetworkManager.singleton.StopHost(); } else { NetworkManager.singleton.StopClient(); } }); }); }
/// <summary> /// Callback for when the exit game button is pressed. /// </summary> public void OnExitGameButtonPressed() { OpenPopup <PopupTwoButtons>("PopupTwoButtons", popup => { popup.text.text = "ゲームを終了しますか?"; popup.buttonText.text = "はい"; popup.button2Text.text = "いいえ"; popup.button.onClickEvent.AddListener(() => { if (NetworkingUtils.GetLocalPlayer().isServer) { GameNetworkManager.Instance.StopHost(); } else { GameNetworkManager.Instance.StopClient(); } //追記 SceneManager.LoadScene("Home"); }); popup.button2.onClickEvent.AddListener(() => { popup.Close(); }); }); }
void Start() { Valve.Sockets.Library.Initialize(); Instance = this; NetworkingUtils utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Everything, DebugMessageCallback); }
// Called when player connects to server private void ConnectionCallback() { this.debugWriter.WriteLine("Successfully connected to server"); isConnected = true; debugCallbackDelegate = (type, message) => { if (this.debugWriter != null) { this.debugWriter.WriteLine("Valve Debug - Type: {0}, Message: {1}", type, message); } }; NetworkingUtils utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Important, debugCallbackDelegate); Main.utilityMenu.chat = ""; Main.utilityMenu.previousMessageCount = 0; unsafe { #if DEBUG // From data I saw a typical example of udp packets over the internet would be 0.3% loss, 25% reorder // For testing I'll use 25% reorder, 30ms delay on reorder, 150ms ping, and 0.2% loss // Re-order 25% of packets and add 30ms delay on reordered packets //float reorderPercent = 25f; //int reorderTime = 30; //utils.SetConfiguratioValue(ConfigurationValue.FakePacketReorderSend, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Float, new IntPtr(&reorderPercent)); //utils.SetConfiguratioValue(ConfigurationValue.FakePacketReorderTime, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Int32, new IntPtr(&reorderTime)); //// Fake 150ms ping //int pingTime = 150; //utils.SetConfiguratioValue(ConfigurationValue.FakePacketLagSend, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Int32, new IntPtr(&pingTime)); //// Simulate 0.2% packet loss //float lossPercent = 0.2f; //utils.SetConfiguratioValue(ConfigurationValue.FakePacketLossSend, ConfigurationScope.Global, IntPtr.Zero, ConfigurationDataType.Float, new IntPtr(&lossPercent)); #endif int sendRateMin = 0; int sendRateMax = 209715200; int sendBufferSize = 10485760; 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)); } }
public void SubmitText() { var localPlayer = NetworkingUtils.GetHumanLocalPlayer(); if (localPlayer != null) { var msg = new SendChatTextMessage(); msg.senderNetId = localPlayer.netId; msg.text = inputField.text; if (msg.text.Length > maxChatMessageLength) { msg.text = msg.text.Substring(0, maxChatMessageLength); } NetworkManager.singleton.client.Send(NetworkProtocol.SendChatTextMessage, msg); inputField.text = string.Empty; inputField.ActivateInputField(); } }
public void SendText(NetworkInstanceId senderNetId, string text) { var go = Instantiate(textLinePrefab) as GameObject; go.transform.SetParent(scrollViewContent.transform, false); go.GetComponent <TextMeshProUGUI>().text = text; scrollView.velocity = new Vector2(0.0f, 1000.0f); var localPlayer = NetworkingUtils.GetHumanLocalPlayer(); if (senderNetId == localPlayer.netId) { go.GetComponent <TextMeshProUGUI>().color = playerTextColor; } else { go.GetComponent <TextMeshProUGUI>().color = opponentTextColor; } }
void Start() { Library.Initialize(); ushort port = 8080; this.client = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::1", port); this.connection = client.Connect(ref address); this.status = (info, context) => { switch (info.connectionInfo.state) { case ConnectionState.None: break; case ConnectionState.Connected: Debug.Log("Client connected to server - ID: " + connection); break; case ConnectionState.ClosedByPeer: client.CloseConnection(connection); Debug.Log("Client disconnected from server"); break; case ConnectionState.ProblemDetectedLocally: client.CloseConnection(connection); Debug.Log("Client unable to connect"); break; } }; DebugCallback debug = (type, message) => { Debug.Log("Debug - Type: " + type + ", Message: " + message); }; NetworkingUtils utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Everything, debug); }
/// <summary> /// Callback for when the end turn button is pressed. /// </summary> public void OnEndTurnButtonPressed() { var localPlayer = NetworkingUtils.GetLocalPlayer() as DemoHumanPlayer; if (localPlayer != null) { //var maxHandSize = GameManager.Instance.Config.properties.maxHandSize; /*if (localPlayer.HandSize > maxHandSize) * { * var diff = localPlayer.HandSize - maxHandSize; * if (diff == 1) * WindowUtils.OpenAlertDialog("You need to discard " + diff + " card from your hand."); * else * WindowUtils.OpenAlertDialog("You need to discard " + diff + " cards from your hand."); * }*/ localPlayer.StopTurn(); } }
void StartServer() { Debug.Log("Starting server..."); utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Message, debug); status = OnServerStatusUpdate; utils.SetStatusCallback(status); server = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::0", port); listenSocket = server.CreateListenSocket(ref address); //connectedPollGroup = server.CreatePollGroup(); }
/// <summary> /// Callback for when the exit game button is pressed. /// </summary> public void OnExitGameButtonPressed() { OpenPopup <PopupTwoButtons>("PopupTwoButtons", popup => { popup.text.text = "Do you want to leave this game?"; popup.buttonText.text = "Yes"; popup.button2Text.text = "No"; popup.button.onClickEvent.AddListener(() => { if (NetworkingUtils.GetLocalPlayer().isServer) { GameNetworkManager.Instance.StopHost(); } else { GameNetworkManager.Instance.StopClient(); } }); popup.button2.onClickEvent.AddListener(() => { popup.Close(); }); }); }
protected virtual void OnMoveCard(NetworkMessage netMsg) { var msg = netMsg.ReadMessage <MoveCardMessage>(); if (msg != null) { // Only the current player can summon cards. if (netMsg.conn.connectionId != server.gameState.currentPlayer.connectionId) { return; } var player = server.gameState.players.Find(x => x.netId == msg.playerNetId); var originZone = player.zones[msg.originZoneId]; var destinationZone = player.zones[msg.destinationZoneId]; var card = originZone.cards.Find(x => x.instanceId == msg.cardInstanceId); if (card != null) { var gameConfig = GameManager.Instance.config; var libraryCard = gameConfig.GetCard(card.cardId); var cost = libraryCard.costs.Find(x => x is PayResourceCost); if (cost != null) { var payResourceCost = cost as PayResourceCost; player.stats[payResourceCost.statId].baseValue -= payResourceCost.value; } var cardMovedMsg = new CardMovedMessage(); cardMovedMsg.playerNetId = msg.playerNetId; cardMovedMsg.card = NetworkingUtils.GetNetCard(card); cardMovedMsg.originZoneId = originZone.zoneId; cardMovedMsg.destinationZoneId = destinationZone.zoneId; cardMovedMsg.targetInfo = msg.targetInfo; server.SafeSendToClient(server.gameState.currentOpponent, NetworkProtocol.CardMoved, cardMovedMsg); server.effectSolver.MoveCard(player.netId, card, originZone.name, destinationZone.name, new List <int>(msg.targetInfo)); } } }
public void ConnectToServer(string username, OnConnect onConnect, OnDisconnect onDisconnect, OnReject onReject) { this.onConnect = onConnect; this.onDisconnect = onDisconnect; this.onReject = onReject; utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Message, debug); Reset(); client = new NetworkingSockets(); Address address = new Address(); address.SetAddress(serverIP, serverport); status = OnClientStatusUpdate; utils.SetStatusCallback(status); connection = client.Connect(ref address); }
public override void OnEndGame(EndGameMessage msg) { base.OnEndGame(msg); var scene = GameObject.Find("GameScene").GetComponent <GameScene>(); scene.OpenPopup <PopupOneButton>("PopupOneButton", popup => { if (msg.winnerPlayerIndex == playerInfo.netId) { popup.text.text = "人生の勝利者"; } else { popup.text.text = "負け犬"; } popup.buttonText.text = "閉じる"; popup.button.onClickEvent.AddListener(() => { if (NetworkingUtils.GetLocalPlayer().isServer) { NetworkManager.singleton.StopHost(); } else { NetworkManager.singleton.StopClient(); } //追記 SceneManager.LoadScene("Home"); } ); }); }
/// <summary> /// Called when the game starts. /// </summary> /// <param name="msg">Start game message.</param> public override void OnStartGame(StartGameMessage msg) { base.OnStartGame(msg); humanPlayer = NetworkingUtils.GetHumanLocalPlayer(); }
public void Execute(Entity entity, int index, ref NetworkClientConnection clientConnection) { if (!serverEndPoint.IsValid) { // TODO: disconnect if the server is not running on the end point commandBuffer.DestroyEntity(index, entity); } else { DataStreamReader stream; NetworkEvent.Type command; while ((command = driver.PopEventForConnection(clientConnection.connection, out stream)) != NetworkEvent.Type.Empty) { if (command == NetworkEvent.Type.Connect) { int lengthOfMsg = sizeof(int); // in bytes, one int, just for the command type, not including the length integer itself byte[] lengthAsBytes = BitConverter.GetBytes(lengthOfMsg); byte[] cmdTypeAsBytes = BitConverter.GetBytes(CommandType.SpawnNewPlayer); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthAsBytes); Array.Reverse(cmdTypeAsBytes); } byte[] result = NetworkingUtils.CombineBytes(lengthAsBytes, cmdTypeAsBytes); DataStreamWriter data = new DataStreamWriter(sizeof(byte) * result.Length, Allocator.Temp); data.Write(result); Debug.Log("size of result " + sizeof(byte) * result.Length); Debug.Log("Sending confirmation of connection to server"); driver.Send(NetworkPipeline.Null, clientConnection.connection, data); } else if (command == NetworkEvent.Type.Data) { /* * Structure of a message to be sent over the server * [size of message, not including this part, sizeof(int)][command type sizeof(int)][other data] */ DataStreamReader.Context readerCtx = default(DataStreamReader.Context); byte[] lengthOfDataAsBytes = stream.ReadBytesAsArray(ref readerCtx, sizeof(int)); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthOfDataAsBytes); } int lengthOfData = BitConverter.ToInt32(lengthOfDataAsBytes, 0); byte[] dataRead = stream.ReadBytesAsArray(ref readerCtx, lengthOfData); byte[] cmdTypeRead = new byte[sizeof(int)]; Buffer.BlockCopy(dataRead, 0, cmdTypeRead, 0, sizeof(int)); if (BitConverter.IsLittleEndian) { Array.Reverse(cmdTypeRead); } int commandType = BitConverter.ToInt32(cmdTypeRead, 0); if (commandType == CommandType.SpawnNewPlayer) { byte[] idAsBytes = new byte[sizeof(int)]; Buffer.BlockCopy(dataRead, sizeof(int), idAsBytes, 0, sizeof(int)); if (BitConverter.IsLittleEndian) { Array.Reverse(idAsBytes); } int id = BitConverter.ToInt32(idAsBytes, 0); Debug.Log("player id from server " + id); commandBuffer.SetComponent(index, entity, new NetworkClientConnection { networkId = id }); } } else if (command == NetworkEvent.Type.Disconnect) { commandBuffer.DestroyEntity(index, entity); } } } }
public void Execute(Entity entity, int index, ref NetworkServerConnection serverConnection) { DataStreamReader stream; NetworkEvent.Type command; while ((command = driver.PopEventForConnection(serverConnection.connection, out stream)) != NetworkEvent.Type.Empty) { if (command == NetworkEvent.Type.Data) { /* * Structure of a message to be sent over the server * [size of message, not including this part, sizeof(int)][command type sizeof(int)][other data] */ Debug.Log("data command on server"); DataStreamReader.Context readerCtx = default(DataStreamReader.Context); byte[] lengthOfDataAsBytes = stream.ReadBytesAsArray(ref readerCtx, sizeof(int)); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthOfDataAsBytes); } int lengthOfData = BitConverter.ToInt32(lengthOfDataAsBytes, 0); byte[] dataRead = stream.ReadBytesAsArray(ref readerCtx, lengthOfData); byte[] cmdTypeRead = new byte[sizeof(int)]; Buffer.BlockCopy(dataRead, 0, cmdTypeRead, 0, sizeof(int)); if (BitConverter.IsLittleEndian) { Array.Reverse(cmdTypeRead); } int commandType = BitConverter.ToInt32(cmdTypeRead, 0); Debug.Log("command type received " + commandType); if (commandType == CommandType.SpawnNewPlayer) { int networkId = id[0]; byte[] cmdTypeAsBytes = BitConverter.GetBytes(CommandType.SpawnNewPlayer); byte[] idAsBytes = BitConverter.GetBytes(networkId); if (BitConverter.IsLittleEndian) { Array.Reverse(cmdTypeAsBytes); Array.Reverse(idAsBytes); } byte[] result = NetworkingUtils.CombineBytes(cmdTypeAsBytes, idAsBytes); int lengthOfMsg = result.Length * sizeof(byte); // in bytes, one int, just for the command type and the id byte[] lengthAsBytes = BitConverter.GetBytes(lengthOfMsg); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthAsBytes); } result = NetworkingUtils.CombineBytes(lengthAsBytes, result); DataStreamWriter data = new DataStreamWriter(sizeof(byte) * result.Length, Allocator.Temp); data.Write(result); id[0] += 1; driver.Send(NetworkPipeline.Null, serverConnection.connection, data); commandBuffer.SetComponent(index, entity, new NetworkServerConnection { networkId = networkId }); } } else if (command == NetworkEvent.Type.Disconnect) { commandBuffer.DestroyEntity(index, entity); } } }
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(); } } }
public void ServerLoop() { Library.Initialize(); server = new NetworkingSockets(); Address address = new Address(); //Console.WriteLine($"Gameplay port: {Server.port}, File Server Port: {(ushort)(Server.port + 1)}"); address.SetAddress("::0", (ushort)(Server.port + 1)); listenSocket = server.CreateListenSocket(ref address); pollGroup = server.CreatePollGroup(); NetworkingUtils utils = new NetworkingUtils(); unsafe { int sendRateMin = 512000; int sendRateMax = Server.FILE_MAX_UPLOAD; utils.SetConfigurationValue(ConfigurationValue.SendRateMin, ConfigurationScope.ListenSocket, new IntPtr(listenSocket), ConfigurationDataType.Int32, new IntPtr(&sendRateMin)); utils.SetConfigurationValue(ConfigurationValue.SendRateMax, ConfigurationScope.ListenSocket, new IntPtr(listenSocket), ConfigurationDataType.Int32, new IntPtr(&sendRateMax)); } StatusCallback status = StatusCallbackFunction; MessageCallback messageCallback = (in NetworkingMessage netMessage) => { byte[] message = new byte[netMessage.length]; netMessage.CopyTo(message); if ((OpCode)message[0] == OpCode.Connect) { uint originalConnection = BitConverter.ToUInt32(message, 1); Player newPlayer = null; foreach (Player player in mainServer.players) { if (player != null && player.connection == originalConnection) { player.fileConnection = netMessage.connection; newPlayer = player; break; } } if (newPlayer == null) { //Console.WriteLine("Connection on file server doesn't exist on gameplay server"); server.CloseConnection(netMessage.connection); } else { foreach (Player player in mainServer.players) { if (player != null && player.playerID != newPlayer.playerID && player.completedGearStream) { player.SendGear(newPlayer.fileConnection, server); } } foreach (Plugin plugin in mainServer.loadedPlugins) { if (plugin.hash != "" && plugin.dependencyFile != "") { byte[] hashBytes = ASCIIEncoding.ASCII.GetBytes(plugin.hash); byte[] hashMessage = new byte[hashBytes.Length + 2]; hashMessage[0] = (byte)OpCode.PluginHash; hashMessage[1] = plugin.pluginID; Array.Copy(hashBytes, 0, hashMessage, 2, hashBytes.Length); server.SendMessageToConnection(newPlayer.fileConnection, hashMessage, SendFlags.Reliable); } } } } else if ((OpCode)message[0] == OpCode.StillAlive) { server.SendMessageToConnection(netMessage.connection, message, SendFlags.Unreliable | SendFlags.NoNagle); } else { foreach (Player player in mainServer.players) { if (player != null && player.fileConnection == netMessage.connection) { mainServer.ProcessMessage(message, player.playerID, mainServer.server); } } } }; Stopwatch fileServerLoopTime = new Stopwatch(); while (mainServer.RUNNING) { fileServerLoopTime.Restart(); server.DispatchCallback(status); server.ReceiveMessagesOnPollGroup(pollGroup, messageCallback, 256); SpinWait.SpinUntil(() => fileServerLoopTime.Elapsed.TotalMilliseconds >= 1, 1); } }
public void ServerLoop() { Library.Initialize(); server = new NetworkingSockets(); Address address = new Address(); //Console.WriteLine($"Gameplay port: {Server.port}, File Server Port: {(ushort)(Server.port + 1)}"); address.SetAddress("::0", (ushort)(Server.port + 1)); listenSocket = server.CreateListenSocket(ref address); pollGroup = server.CreatePollGroup(); NetworkingUtils utils = new NetworkingUtils(); unsafe { int sendRateMin = 512000; int sendRateMax = Server.FILE_MAX_UPLOAD; utils.SetConfigurationValue(ConfigurationValue.SendRateMin, ConfigurationScope.ListenSocket, new IntPtr(listenSocket), ConfigurationDataType.Int32, new IntPtr(&sendRateMin)); utils.SetConfigurationValue(ConfigurationValue.SendRateMax, ConfigurationScope.ListenSocket, new IntPtr(listenSocket), ConfigurationDataType.Int32, new IntPtr(&sendRateMax)); } StatusCallback status = StatusCallbackFunction; MessageCallback messageCallback = (in NetworkingMessage netMessage) => { byte[] message = new byte[netMessage.length]; netMessage.CopyTo(message); if ((OpCode)message[0] == OpCode.Connect) { uint originalConnection = BitConverter.ToUInt32(message, 1); Player newPlayer = null; foreach (Player player in mainServer.players) { if (player != null && player.connection == originalConnection) { player.fileConnection = netMessage.connection; newPlayer = player; break; } } if (newPlayer == null) { //Console.WriteLine("Connection on file server doesn't exist on gameplay server"); server.CloseConnection(netMessage.connection); } else { foreach (Player player in mainServer.players) { if (player != null && player.playerID != newPlayer.playerID && player.completedGearStream) { player.SendGear(newPlayer.fileConnection, server); } } } } else if ((OpCode)message[0] == OpCode.StillAlive) { server.SendMessageToConnection(netMessage.connection, message, SendFlags.Unreliable | SendFlags.NoNagle); } else { foreach (Player player in mainServer.players) { if (player != null && player.fileConnection == netMessage.connection) { mainServer.ProcessMessage(message, player.playerID, mainServer.server); } } } }; while (mainServer.RUNNING) { server.DispatchCallback(status); server.ReceiveMessagesOnPollGroup(pollGroup, messageCallback, 256); } }