Example #1
0
        private void Peer_OnReceived(object Sender, byte[] Packet)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Player         Player;

            if (Connection.StateObject is null)
            {
                BinaryInput Input = new BinaryInput(Packet);
                Guid        PlayerId;
                IPAddress   PlayerRemoteAddress;
                IPEndPoint  PlayerRemoteEndpoint;

                try
                {
                    PlayerId             = Input.ReadGuid();
                    PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                    PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
                }
                catch (Exception)
                {
                    Connection.Dispose();
                    return;
                }

                if (Input.BytesLeft == 0)
                {
                    Packet = null;
                }
                else
                {
                    Packet = Input.GetRemainingData();
                }

                bool AllConnected;

                lock (this.remotePlayersByEndpoint)
                {
                    if (!this.playersById.TryGetValue(PlayerId, out Player))
                    {
                        Connection.Dispose();
                        return;
                    }

                    if (Player.Connection is null)
                    {
                        this.connectionCount++;
                    }
                    else
                    {
                        Player.Connection.Dispose();
                    }

                    Player.Connection         = Connection;
                    Connection.StateObject    = Player;
                    Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

                    AllConnected = this.connectionCount + 1 == this.playerCount;
                }

                MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;
                if (h != null)
                {
                    try
                    {
                        h(this, Player);
                    }
                    catch (Exception ex)
                    {
                        Events.Log.Critical(ex);
                    }
                }

                if (AllConnected)
                {
                    this.State = MultiPlayerState.Ready;
                }

                if (Packet is null)
                {
                    return;
                }
            }
            else
            {
                Player = (Player)Connection.StateObject;
            }

            this.GameDataReceived(Player, Connection, Packet);
        }