Example #1
0
        /// <summary>
        ///     When we get a message from a client, we handle the message here
        ///     and perform any necessary tasks.
        /// </summary>
        private void ListenerOnNetworkReceiveEvent(NetPeer peer, NetDataReader reader)
        {
            try
            {
                // Handle ConnectionRequest as special case
                if (reader.Data[0] == 0)
                {
                    Command.Parse(reader.Data, out CommandHandler handler, out byte[] message);
                    ConnectionRequestHandler requestHandler = (ConnectionRequestHandler)handler;
                    requestHandler.HandleOnServer(message, peer);
                    return;
                }

                // Parse this message
                ConnectedPlayers.TryGetValue(peer.ConnectId, out Player player);
                Command.ParseOnServer(reader.Data, player);

                // Send this message to all other clients
                var peers = _netServer.GetPeers();
                foreach (var client in peers)
                {
                    // Don't send the message back to the client that sent it.
                    if (client.ConnectId == peer.ConnectId)
                    {
                        continue;
                    }

                    // Send the message so the other client can stay in sync
                    client.Send(reader.Data, SendOptions.ReliableOrdered);
                }
            }
            catch (Exception ex)
            {
                CSM.Log($"Encountered an error while reading command from {peer.EndPoint.Host}:{peer.EndPoint.Port}:");
                CSM.Log(ex.ToString());
            }
        }