Exemplo n.º 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, NetPacketReader reader, DeliveryMethod deliveryMethod)
        {
            try
            {
                // Handle ConnectionRequest as special case
                if (reader.PeekByte() == 0)
                {
                    Command.Parse(reader, out CommandHandler handler, out byte[] message);
                    ConnectionRequestHandler requestHandler = (ConnectionRequestHandler)handler;
                    requestHandler.HandleOnServer(message, peer);
                    return;
                }

                // Parse this message
                ConnectedPlayers.TryGetValue(peer.Id, out Player player);
                bool relayOnServer = Command.ParseOnServer(reader, player);

                if (relayOnServer)
                {
                    // Copy relevant message part (exclude protocol headers)
                    byte[] data = new byte[reader.UserDataSize];
                    Array.Copy(reader.RawData, reader.UserDataOffset, data, 0, reader.UserDataSize);

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

                        // Send the message so the other client can stay in sync
                        client.Send(data, DeliveryMethod.ReliableOrdered);
                    }
                }
            }
            catch (Exception ex)
            {
                ChatLogPanel.PrintGameMessage(ChatLogPanel.MessageType.Error, "Error while parsing command. See log.");
                _logger.Error(ex, $"Encountered an error while reading command from {peer.EndPoint.Address}:{peer.EndPoint.Port}:");
            }
        }