Beispiel #1
0
        public override IEncodable Decode(BinaryInput stream)
        {
            base.Decode(stream);
            value = stream.ReadUInt16();

            return(this);
        }
Beispiel #2
0
        private Player Deserialize(BinaryInput Input)
        {
            IPAddress  PublicAddress  = IPAddress.Parse(Input.ReadString());
            ushort     PublicPort     = Input.ReadUInt16();
            IPEndPoint PublicEndpoint = new IPEndPoint(PublicAddress, PublicPort);

            IPAddress  LocalAddress  = IPAddress.Parse(Input.ReadString());
            ushort     LocalPort     = Input.ReadUInt16();
            IPEndPoint LocalEndpoint = new IPEndPoint(LocalAddress, LocalPort);

            Guid PlayerId = Input.ReadGuid();
            bool LocalPlayer = PlayerId == this.localPlayer.PlayerId;
            int  i, c = (int)Input.ReadUInt();

            KeyValuePair <string, string>[] PlayerMetaInfo = LocalPlayer ? null : new KeyValuePair <string, string> [c];
            string Key, Value;

            for (i = 0; i < c; i++)
            {
                Key   = Input.ReadString();
                Value = Input.ReadString();
                if (!LocalPlayer)
                {
                    PlayerMetaInfo[i] = new KeyValuePair <string, string>(Key, Value);
                }
            }

            if (LocalPlayer)
            {
                return(null);
            }
            else
            {
                return(new Player(PlayerId, PublicEndpoint, LocalEndpoint, PlayerMetaInfo));
            }
        }
Beispiel #3
0
        private void Connection_OnReceived(object Sender, byte[] Packet)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(Packet);

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

            Player Player = (Player)Connection.StateObject;

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

                Player.Connection = Connection;
            }

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

            Connection.OnReceived -= new BinaryEventHandler(Connection_OnReceived);
            Connection.OnReceived += new BinaryEventHandler(Peer_OnReceived);

            Connection.OnSent += new BinaryEventHandler(Connection_OnSent);

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (h != null)
            {
                try
                {
                    h(this, Player);
                }
                catch (Exception ex)
                {
                    Events.Log.Critical(ex);
                }
            }
        }
Beispiel #4
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);
        }
		private bool ProcessInputPacket()
		{
			try
			{
				BinaryInput Packet = new BinaryInput(this.inputPacket);
				MqttHeader Header = MqttHeader.Parse(Packet);

				switch (Header.ControlPacketType)
				{
					case MqttControlPacketType.CONNECT:
					default:
						throw new Exception("Received command from server that is not handled: " + Header.ControlPacketType.ToString());

					case MqttControlPacketType.CONNACK:
						bool SessionPresent = (Packet.ReadByte() & 1) != 0;
						byte ReturnCode = Packet.ReadByte();

						try
						{
							switch (ReturnCode)
							{
								case 0:
									this.State = MqttState.Connected;
									this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
									break;

								case 1:
									throw new IOException("Connection Refused, unacceptable protocol version.");

								case 2:
									throw new IOException("Connection Refused, identifier rejected.");

								case 3:
									throw new IOException("Connection Refused, Server unavailable.");

								case 4:
									throw new IOException("Connection Refused, bad user name or password.");

								case 5:
									throw new IOException("Connection Refused, not authorized.");

								default:
									throw new IOException("Unrecognized error code returned: " + ReturnCode.ToString());
							}
						}
						catch (Exception ex)
						{
							this.ConnectionError(ex);
							this.stream.Close();
							this.client.Close();
							return false;
						}
						break;

					case MqttControlPacketType.PINGREQ:
						this.PINGRESP();
						break;

					case MqttControlPacketType.PINGRESP:
						EventHandler h = this.OnPingResponse;
						if (h != null)
						{
							try
							{
								h(this, new EventArgs());
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.PUBLISH:
						string Topic = Packet.ReadString();
						
						if (Header.QualityOfService > MqttQualityOfService.AtMostOne)
							Header.PacketIdentifier = Packet.ReadUInt16();
						else
							Header.PacketIdentifier = 0;

						int c = Packet.BytesLeft;
						byte[] Data = Packet.ReadBytes(c);
						MqttContent Content = new MqttContent(Header, Topic, Data);

						switch (Header.QualityOfService)
						{
							case MqttQualityOfService.AtMostOne:
								this.ContentReceived(Content);
								break;

							case MqttQualityOfService.AtLeastOne:
								this.PUBACK(Header.PacketIdentifier);
								this.ContentReceived(Content);
								break;

							case MqttQualityOfService.ExactlyOne:
								lock (this.contentCache)
								{
									this.contentCache[Header.PacketIdentifier] = Content;
								}
								this.PUBREC(Header.PacketIdentifier);
								break;
						}
						break;

					case MqttControlPacketType.PUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						PacketAcknowledgedEventHandler h2 = this.OnPublished;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.PUBREC:
						this.PacketDelivered(Header.PacketIdentifier);
						this.PUBREL(Header.PacketIdentifier);
						break;

					case MqttControlPacketType.PUBREL:
						lock (this.contentCache)
						{
							if (this.contentCache.TryGetValue(Header.PacketIdentifier, out Content))
								this.contentCache.Remove(Header.PacketIdentifier);
							else
								Content = null;
						}
						this.PUBCOMP(Header.PacketIdentifier);

						if (Content != null)
							this.ContentReceived(Content);
						break;

					case MqttControlPacketType.PUBCOMP:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnPublished;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.SUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnSubscribed;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.UNSUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnUnsubscribed;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;
				}
			}
			catch (Exception ex)
			{
				this.Error(ex);
			}

			return true;
		}
        private bool ProcessInputPacket()
        {
            try
            {
                BinaryInput Packet = new BinaryInput(this.inputPacket);
                MqttHeader  Header = MqttHeader.Parse(Packet);

                switch (Header.ControlPacketType)
                {
                case MqttControlPacketType.CONNECT:
                default:
                    throw new Exception("Received command from server that is not handled: " + Header.ControlPacketType.ToString());

                case MqttControlPacketType.CONNACK:
                    bool SessionPresent = (Packet.ReadByte() & 1) != 0;
                    byte ReturnCode     = Packet.ReadByte();

                    try
                    {
                        switch (ReturnCode)
                        {
                        case 0:
                            this.State    = MqttState.Connected;
                            this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
                            break;

                        case 1:
                            throw new IOException("Connection Refused, unacceptable protocol version.");

                        case 2:
                            throw new IOException("Connection Refused, identifier rejected.");

                        case 3:
                            throw new IOException("Connection Refused, Server unavailable.");

                        case 4:
                            throw new IOException("Connection Refused, bad user name or password.");

                        case 5:
                            throw new IOException("Connection Refused, not authorized.");

                        default:
                            throw new IOException("Unrecognized error code returned: " + ReturnCode.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        this.ConnectionError(ex);
                        this.stream.Close();
                        this.client.Close();
                        return(false);
                    }
                    break;

                case MqttControlPacketType.PINGREQ:
                    this.PINGRESP();
                    break;

                case MqttControlPacketType.PINGRESP:
                    EventHandler h = this.OnPingResponse;
                    if (!(h is null))
                    {
                        try
                        {
                            h(this, new EventArgs());
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.PUBLISH:
                    string Topic = Packet.ReadString();

                    if (Header.QualityOfService > MqttQualityOfService.AtMostOne)
                    {
                        Header.PacketIdentifier = Packet.ReadUInt16();
                    }
                    else
                    {
                        Header.PacketIdentifier = 0;
                    }

                    int         c       = Packet.BytesLeft;
                    byte[]      Data    = Packet.ReadBytes(c);
                    MqttContent Content = new MqttContent(Header, Topic, Data);

                    switch (Header.QualityOfService)
                    {
                    case MqttQualityOfService.AtMostOne:
                        this.ContentReceived(Content);
                        break;

                    case MqttQualityOfService.AtLeastOne:
                        this.PUBACK(Header.PacketIdentifier);
                        this.ContentReceived(Content);
                        break;

                    case MqttQualityOfService.ExactlyOne:
                        lock (this.contentCache)
                        {
                            this.contentCache[Header.PacketIdentifier] = Content;
                        }
                        this.PUBREC(Header.PacketIdentifier);
                        break;
                    }
                    break;

                case MqttControlPacketType.PUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    PacketAcknowledgedEventHandler h2 = this.OnPublished;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.PUBREC:
                    this.PacketDelivered(Header.PacketIdentifier);
                    this.PUBREL(Header.PacketIdentifier);
                    break;

                case MqttControlPacketType.PUBREL:
                    lock (this.contentCache)
                    {
                        if (this.contentCache.TryGetValue(Header.PacketIdentifier, out Content))
                        {
                            this.contentCache.Remove(Header.PacketIdentifier);
                        }
                        else
                        {
                            Content = null;
                        }
                    }
                    this.PUBCOMP(Header.PacketIdentifier);

                    if (!(Content is null))
                    {
                        this.ContentReceived(Content);
                    }
                    break;

                case MqttControlPacketType.PUBCOMP:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnPublished;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.SUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnSubscribed;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.UNSUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnUnsubscribed;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }

            return(true);
        }
        private async Task <bool> Connection_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(BinaryTcpClient.ToArray(Buffer, Offset, Count));

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

            Player Player = (Player)Connection.StateObject;

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

                Player.Connection = Connection;
            }

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

            Connection.OnReceived -= this.Connection_OnReceived;
            Connection.OnReceived += this.Peer_OnReceived;
            Connection.OnSent     += this.Connection_OnSent;

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            await Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (!(h is null))
            {
                try
                {
                    await h(this, Player);
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }

            return(true);
        }