ReadBytes() public méthode

Reads the specified number of bytes
public ReadBytes ( int numberOfBytes ) : byte[]
numberOfBytes int
Résultat byte[]
 protected override void ReadData(NetIncomingMessage Message)
 {
     texture.Read(Message);
     int datalen = Message.ReadInt32();
     byte[] data = Message.ReadBytes(datalen);
     img = GetBitmap(data);
 }
		public void Dispatch(NetIncomingMessage message)
		{
			//The message.LengthBytes - message.PositionInBytes is from GladNet1
			//We need to read the byte[] chunk that is from the current position to the end.
			//For why we do this read this old exerp from GladNet2:
			//"Due to message recycling we cannot trust the internal array of data to be of only the information that should be used for this package.
			//We can trust the indicated size, not the length of .Data, and get a byte[] that represents the sent [Data].
			//However, this will incur a GC penalty which may become an issue; more likely to be an issue on clients."
			byte[] bytes = message.ReadBytes(message.LengthBytes - message.PositionInBytes);

			NetworkMessage gladNetNetworkMessage = null;
					
			try
			{
				gladNetNetworkMessage = deserializer.Deserialize<NetworkMessage>(bytes);
			}
			catch (Exception e)
			{
				//This is only for debug builds because in release end-user exploiters might send garbage and generate many exceptions
#if DEBUG || DEBUGBUILD
				throw new InvalidOperationException($"Could not deserialize message from ID: {message.SenderConnection?.RemoteUniqueIdentifier}");
#else
				//supress exception
				//Do NOT disconnect the peer due to malformed messages
				//Malicious users will spoof the messages of others in that case
#endif
			}

			gladNetNetworkMessage?.Dispatch(this, new LidgrenMessageDetailsAdapter(message, false)); //TODO: Encryption implementation
		}
 public override void ReadPayload(NetIncomingMessage message)
 {
     base.ReadPayload(message);
     Image = message.ReadBytes(message.ReadInt32());
     Number = message.ReadUInt32();
     SendIndex = message.ReadInt32();
 }
Exemple #4
0
        private void Route1Tile(NetIncomingMessage msg)
        {
            //int TileID = Convert.ToInt32(msg.ReadBytes(4));
            //byte EventType = msg.ReadByte();

            TileEngine.TileEngine.EventManager.Enqueue(msg.ReadBytes(msg.LengthBytes - msg.PositionInBytes));
        }
			public override void DataReceived ( NetCommand command, NetIncomingMessage msg )
			{
				if (command==NetCommand.Snapshot) {
					
					var frame		=	msg.ReadUInt32();
					var prevFrame	=	msg.ReadUInt32();
					var ackCmdID	=	msg.ReadUInt32();
					var serverTicks	=	msg.ReadInt64();
					var size		=	msg.ReadInt32();

					//Log.Warning("{0}", offsetTicks );

					if (prevFrame!=0) {
						Log.Warning("Bad initial snapshot. Previous frame does not equal zero.");
						return;
					}
					if (ackCmdID!=0) {
						Log.Warning("Bad command ID {0}. Command ID for initial snapshot must be zero.", ackCmdID);
						return;
					}

					//	read snapshot :
					var snapshot	=	NetDeflate.Decompress( msg.ReadBytes(size) );

					//	initial snapshot contains atom table :
					gameClient.Atoms	=	new AtomCollection( msg );


					gameClient.SetState( new Active( gameClient, frame, snapshot, serverTicks ) );
				}

				if (command==NetCommand.Notification) {
					gameClient.FeedNotification( msg.ReadString() );
				}
			}
 public static new Packet FromNetBuffer(NetIncomingMessage incomingMessage)
 {
     var result =
         (GameMap) SerializationHelper.ByteArrayToObject(incomingMessage.ReadBytes(incomingMessage.ReadInt32()));
     var id = incomingMessage.ReadUInt64();
     var packet = new SendMapPacket(result, id);
     return packet;
 }
Exemple #7
0
        private static void HandleAudioPacket(NetIncomingMessage msg)
        {
            Console.WriteLine("Received: {0}", msg.LengthBytes);

            var data = msg.ReadBytes(msg.LengthBytes);
            var decoded = codec.Decode(data);

            waveProvider.AddSamples(decoded, 0, decoded.Length);
        }
 protected override void ReadData(NetIncomingMessage Message)
 {
     if (!Guid.TryParse(Message.ReadString(), out parent)) {
         throw new Exception("Failed to parse parent guid for addtexture");
     }
     texture.Read(Message);
     int datalen = Message.ReadInt32();
     byte[] data = Message.ReadBytes(datalen);
     texture.Load(GetBitmap(data));
 }
        public static new Packet FromNetBuffer(NetIncomingMessage incomingMessage)
        {
            var type = (ContentType) incomingMessage.ReadByte();
            var length = incomingMessage.ReadInt32();
            var bytes = incomingMessage.ReadBytes(length);

            var o = (List<EditorTemplateEntry>) SerializationHelper.ByteArrayToObject(bytes);
            var packet = new ContentListResultPacket(o, type);

            return packet;
        }
        public static new Packet FromNetBuffer(NetIncomingMessage incomingMessage)
        {
            var length = incomingMessage.ReadInt32();
            var bytes = incomingMessage.ReadBytes(length);
            var type = (ContentType) incomingMessage.ReadByte();

            var o = SerializationHelper.ByteArrayToObject(bytes) as IContentTemplate;
            var packet = new ContentSaveRequestPacket(o, type);

            return packet;
        }
 /// <summary>
 /// Der Inhalt der Nachricht, welcher ein Objekt darstellt
 /// (ganze Nachricht mit Offset der Länge der Bezeichnung z.B. "newDirection"),
 /// wird wieder in ein Objekt deserialisiert. Die Rückgabe muss anschliessend
 /// gecastet werden. Bsp. (Direction)networkManager.Deserialize(msg,msgString)
 /// </summary>
 /// <param name="msg">Eingegangene Nachricht (von IncomingMessageQueue)</param>
 /// <param name="msgString">msg.ReadString()</param>
 /// <returns>Object</returns>
 public object Deserialize(NetIncomingMessage msg, string msgString)
 {
     int offset = msgString.ToArray().Length + 1;
     BinaryFormatter bin = new BinaryFormatter();
     MemoryStream mem = new MemoryStream();
     byte[] dataBuffer = new byte[msg.LengthBytes];
     msg.ReadBytes(dataBuffer, offset, msg.LengthBytes - offset);
     mem.Write(dataBuffer, 0, dataBuffer.Length);
     mem.Seek(offset, 0);
     return bin.Deserialize(mem);
 }
Exemple #12
0
        public static GameStateDelta ReadDelta(NetIncomingMessage message)
        {
            uint sequence = message.ReadUInt32();
            uint fromSequence = message.ReadUInt32();
            int length = message.ReadInt32();
            byte[] bytes;
            message.ReadBytes(length, out bytes);

            var delta = new GameStateDelta(bytes);
            delta.Sequence = sequence;
            delta.FromSequence = fromSequence;
            return delta;
        }
        public static MarshalComponentParameter Deserialize(NetIncomingMessage message)
        {
            if (!_serializerInitialized)
            {
                InitSerializer();
            }
            int length = message.ReadInt32();
            byte[] bytes = message.ReadBytes(length);
            var ms = new MemoryStream(bytes);

            //Thank you NetSerializer
            return (MarshalComponentParameter) Serializer.Deserialize(ms);
        }
		public LidgrenNetworkMessageMessageContext(NetIncomingMessage incomingMessage, IDeserializerStrategy deserializer)
			: base(incomingMessage)
		{
			//The message.LengthBytes - message.PositionInBytes is from GladNet1
			//We need to read the byte[] chunk that is from the current position to the end.
			//For why we do this read this old exerp from GladNet2:
			//"Due to message recycling we cannot trust the internal array of data to be of only the information that should be used for this package.
			//We can trust the indicated size, not the length of .Data, and get a byte[] that represents the sent [Data].
			//However, this will incur a GC penalty which may become an issue; more likely to be an issue on clients."
			byte[] bytes = incomingMessage.ReadBytes(incomingMessage.LengthBytes - incomingMessage.PositionInBytes);

			//Deserializer the network message and the payload.
			GeneratedNetworkMessage = deserializer.Deserialize<NetworkMessage>(bytes);
			GeneratedNetworkMessage?.Payload?.Deserialize(deserializer);
		}
        public static new Packet FromNetBuffer(NetIncomingMessage incomingMessage)
        {
            object o = null;
            var locked = incomingMessage.ReadBoolean();
            var type = (ContentType) incomingMessage.ReadByte();

            if (!locked)
            {
                var length = incomingMessage.ReadInt32();
                var bytes = incomingMessage.ReadBytes(length);

                o = SerializationHelper.ByteArrayToObject(bytes);
            }

            var packet = new ContentResultPacket(o, locked, type);

            return packet;
        }
Exemple #16
0
        public void Decode(NetIncomingMessage im)
        {
            map.Width = im.ReadInt16();
            map.Height = im.ReadInt16();
            map.Tiles = new Tile[map.Width, map.Height, 2];

            map.Minimap = new Minimap(map, map.Width, map.Height);
            map.Minimap.Position = new Microsoft.Xna.Framework.Vector2(16, 16);
            for (int z = 0; z < 2; z++)
            {
                for (int y = 0; y < map.Height; y++)
                {
                    byte[] b = im.ReadBytes(map.Width);
                    for (int x = 0; x < map.Width; x++)
                    {
                        if (z == 0)
                            map.Tiles[x, y, 1] = new Tile(BlockType.BlockList[b[x]]);
                        else
                            map.Tiles[x, y, 0] = new Tile(BlockType.BlockList[b[x]]);
                    }
                }
            }
        }
        private bool ValidateHandshakeData(int ptr, int payloadLength, out byte[] hail)
        {
            hail = null;

            // create temporary incoming message
            NetIncomingMessage msg = m_peer.SetupReadHelperMessage(ptr, payloadLength);

            try
            {
                string remoteAppIdentifier    = msg.ReadString();
                long   remoteUniqueIdentifier = msg.ReadInt64();
                InitializeRemoteTimeOffset(msg.ReadSingle());

                int remainingBytes = payloadLength - (msg.PositionInBytes - ptr);
                if (remainingBytes > 0)
                {
                    hail = msg.ReadBytes(remainingBytes);
                }

                if (remoteAppIdentifier != m_peer.m_configuration.AppIdentifier)
                {
                    // wrong app identifier
                    ExecuteDisconnect("Wrong application identifier!", true);
                    return(false);
                }

                m_remoteUniqueIdentifier = remoteUniqueIdentifier;
            }
            catch (Exception ex)
            {
                // whatever; we failed
                ExecuteDisconnect("Handshake data validation failed", true);
                m_peer.LogWarning("ReadRemoteHandshakeData failed: " + ex.Message);
                return(false);
            }
            return(true);
        }
Exemple #18
0
 public override void Read(NetIncomingMessage msg)
 {
     VoiceData = msg.ReadBytes(msg.ReadInt32());
 }
 /// <summary>
 /// Reads the transport into the contents of this type.
 /// </summary>
 public void ReadPayload(NetIncomingMessage message)
 {
     Image = message.ReadBytes(message.ReadInt32());
     Region = new Rectangle(message.ReadInt32(), message.ReadInt32(), message.ReadInt32(), message.ReadInt32());
     Number = message.ReadUInt32();
 }
 public static NetOutgoingMessage CopyIncommingMessage(this NetOutgoingMessage o, NetIncomingMessage inc, int discount = NetWorkingConstants.HeaderSizeinBytes )
 {
     o.Write(inc.ReadBytes(inc.LengthBytes - discount));
     return o;
 }
 private List<object> UnPackParams(NetIncomingMessage message)
 {
     var messageParams = new List<object>();
     while (message.Position < message.LengthBits)
     {
         switch ((NetworkDataType) message.ReadByte())
         {
             case NetworkDataType.d_enum:
                 messageParams.Add(message.ReadInt32()); //Cast from int, because enums are ints.
                 break;
             case NetworkDataType.d_bool:
                 messageParams.Add(message.ReadBoolean());
                 break;
             case NetworkDataType.d_byte:
                 messageParams.Add(message.ReadByte());
                 break;
             case NetworkDataType.d_sbyte:
                 messageParams.Add(message.ReadSByte());
                 break;
             case NetworkDataType.d_ushort:
                 messageParams.Add(message.ReadUInt16());
                 break;
             case NetworkDataType.d_short:
                 messageParams.Add(message.ReadInt16());
                 break;
             case NetworkDataType.d_int:
                 messageParams.Add(message.ReadInt32());
                 break;
             case NetworkDataType.d_uint:
                 messageParams.Add(message.ReadUInt32());
                 break;
             case NetworkDataType.d_ulong:
                 messageParams.Add(message.ReadUInt64());
                 break;
             case NetworkDataType.d_long:
                 messageParams.Add(message.ReadInt64());
                 break;
             case NetworkDataType.d_float:
                 messageParams.Add(message.ReadFloat());
                 break;
             case NetworkDataType.d_double:
                 messageParams.Add(message.ReadDouble());
                 break;
             case NetworkDataType.d_string:
                 messageParams.Add(message.ReadString());
                 break;
             case NetworkDataType.d_byteArray:
                 int length = message.ReadInt32();
                 messageParams.Add(message.ReadBytes(length));
                 break;
         }
     }
     return messageParams;
 }
Exemple #22
0
        private void HandleData(GameTime gameTime, NetIncomingMessage msg)
        {
            MessageType messageType = (MessageType)msg.ReadByte();

            switch (messageType)
            {
                case MessageType.MsgState:
                    {
                        Log.DebugFormat("Got MsgState ({0} bytes)", msg.LengthBytes);

                        // we finished receiving state at this point
                        ServerLinkStatus = NetServerLinkStatus.Connected;

                        break;
                    }

                case MessageType.MsgAddPlayer:
                    {
                        Log.DebugFormat("Got MsgAddPlayer ({0} bytes)", msg.LengthBytes);

                        MsgAddPlayerPacket packet = MsgAddPlayerPacket.Read(msg);

                        FireMessageEvent(gameTime, packet);

                        break;
                    }

                case MessageType.MsgRemovePlayer:
                    {
                        Log.DebugFormat("Got MsgRemovePlayer ({0} bytes)", msg.LengthBytes);

                        MsgRemovePlayerPacket packet = MsgRemovePlayerPacket.Read(msg);

                        FireMessageEvent(gameTime, packet);

                        break;
                    }

                case MessageType.MsgWorld:
                    {
                        Log.DebugFormat("Got MsgWorld ({0} bytes)", msg.LengthBytes);

                        UInt16 mapLength = msg.ReadUInt16();
                        Byte[] rawWorld = new Byte[mapLength];
                        msg.ReadBytes(mapLength, out rawWorld);

                        MemoryStream ms = new MemoryStream(rawWorld);
                        StreamReader sr = new StreamReader(ms);

                        MsgWorldPacket msgWorldEventData = new MsgWorldPacket(mapLength, sr);

                        FireMessageEvent(gameTime, msgWorldEventData);

                        break;
                    }

                case MessageType.MsgPlayerServerUpdate:
                    {
                        MsgPlayerServerUpdatePacket packet = MsgPlayerServerUpdatePacket.Read(msg);

                        FireMessageEvent(gameTime, packet);

                        break;
                    }

                default:
                    // if we get anything else we should fail
                    // protocol version should protect us from unknowns
                    break;

            }
        }
        // BEWARE: Called by network thread.
        private bool OnConnectionMessage(NetIncomingMessage msg)
        {
            if (msg.MessageType == NetIncomingMessageType.Data)
            {
                var workStream = new MemoryStream(msg.ReadBytes(msg.LengthBytes), 0, msg.LengthBytes, false, true);
                var packet = _packetSerializer.Deserialize(workStream) as Packet;
                if (packet != null)
                    OnConnectionReceive(packet);
                return true;
            }

            return false;
        }
        private NetworkMessage ReadMessage(NetIncomingMessage msg)
        {
            switch (msg.MessageType)
            {
                case NetIncomingMessageType.StatusChanged:
                    Status.LastStatus = (ConnectionStatus) msg.ReadByte();

                    switch (Status.LastStatus)
                    {
                        case ConnectionStatus.Connected:
                            OnConnectionUpdate(Status.LastStatus, msg.SenderConnection);

                            // TODO: This is not correct if server
                            Status.Connecting = false;
                            Status.Connected = true;

                            break;
                        case ConnectionStatus.Disconnected:
                            OnConnectionUpdate(Status.LastStatus, msg.SenderConnection);

                            // TODO: This is not correct if server
                            Status.Connecting = false;
                            Status.Connected = false;

                            break;
                        case ConnectionStatus.InitiatedConnect:
                            // TODO: This is not correct if server
                            Status.Connected = false;
                            Status.Connecting = true;

                            break;
                    }

                    return new NetworkMessage
                        {
                            Type = (MessageType) msg.MessageType,
                            Status = Status.LastStatus,
                            Sender = new NetworkConnection {Connection = msg.SenderConnection}
                        };

                case NetIncomingMessageType.DiscoveryRequest:
                        SendDiscoveryResponse(msg.SenderEndPoint);

                    return new NetworkMessage
                        {
                            Type = (MessageType) msg.MessageType,
                            Sender = new NetworkConnection {Connection = msg.SenderConnection}
                        };

                case NetIncomingMessageType.DiscoveryResponse:
                    var discoveryID = msg.ReadString();

                    if (discoveryID == _peerIDString)
                        return null;

                    if (_config.ConnectOnDiscovery)
                        OpenConnection(_config.SysType, msg.SenderEndPoint);

                    if (_discoveryTimeout != null)
                        _discoveryTimeout.Dispose();

                    return new NetworkMessage
                        {
                            Type = (MessageType) msg.MessageType,
                            Sender = new NetworkConnection {RemoteEndPoint = msg.SenderEndPoint},
                            Message = new NetworkMsgType {MsgType = MsgDataTypes.String, ReadString = discoveryID}
                        };

                case NetIncomingMessageType.Data:
                    return new NetworkMessage
                        {
                            Type = (MessageType) msg.MessageType,
                            Sender = new NetworkConnection {Connection = msg.SenderConnection},
                            Message =
                                new NetworkMsgType
                                    {
                                        MsgType = MsgDataTypes.Bytes,
                                        ReadBytes = msg.ReadBytes(msg.LengthBytes)
                                    }
                        };

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.ErrorMessage:
                    return new NetworkMessage
                        {
                            Type = (MessageType) msg.MessageType,
                            Sender = new NetworkConnection(),
                            Message = new NetworkMsgType {MsgType = MsgDataTypes.String, ReadString = msg.ReadString()}
                        };
            }

            return null;
        }
Exemple #25
0
        //Message Handler
        private void MessageReceive(NetIncomingMessage message)
        {
            byte packetHeader;
            try
            {
                packetHeader = message.ReadByte(); //Try read Header
            }
            catch
            {
                return;
            }

            switch ((Network.PacketTypes) packetHeader) //Switch PacketHeaderType
            {
                case Network.PacketTypes.RECEIVEPLAYER: //Receive a new player
                    string name = message.ReadString();
                    long uid = message.ReadInt64();

                    int bufferLength = message.ReadInt32();
                    byte[] buffer = message.ReadBytes(bufferLength);

                    PlayerStore.Add(uid, new Player(name, buffer, 0));

                    Console.WriteLine("Player {0} connected with ID: {1}", name, uid);
                    load.Invoke(new Action(() => load.RefreshDisplay()));
                    break;

                case Network.PacketTypes.GETPOS: //Receive someones score
                    long id = message.ReadInt64();
                    int score = message.ReadInt16();
                    Console.WriteLine(id);

                    PlayerStore[id].Score = score;
                    load.Invoke(new Action(() => RefreshDisplay()));
                    Console.WriteLine("Player: {0} Score: {1}", PlayerStore[id].Name, PlayerStore[id].Score);

                    if (PlayerStore[id].Score >= 100 & Program.SetWinner == false)
                    {
                        Program.Realwinner = PlayerStore[id].Name;
                        Program.SetWinner = true;
                        Program.LeaderBoardList.Add(String.Format("{0} : {1}", Program.Realwinner,
                        globalGameTime));
                        Invoke(new Action(() => LeaderBoard.DataSource = Program.LeaderBoardList));
                    }
                    break;

                case Network.PacketTypes.HOST: //If we receive this then we are the host
                    load.Invoke(new Action(() => load.buttonStart.Visible = true));
                    string fix = message.ReadString();
                    break;

                case Network.PacketTypes.STARTGAME: //Start the Game form.
                    load.Invoke(new Action(() => TheSpacebarGame.Menu.game.Show()));
                    string fix2 = message.ReadString();
                    break;

                case Network.PacketTypes.SCOREWIN: //Someone has Won
                    string person = message.ReadString();
                    Program.Place = message.ReadInt16();

                    if (Program.Place == 1 & person == Program.Ourname)
                    {
                        Program.LeaderBoardList.Add(String.Format("{0} : {1}", person,globalGameTime));
                        Invoke(new Action(() => LeaderBoard.DataSource = Program.LeaderBoardList));
                    }
                    else
                    {
                        Program.LeaderBoardList.Add(String.Format("{0} : {1}", person, globalGameTime));

                        Invoke(new Action(() => LeaderBoard.DataSource = Program.LeaderBoardList));
                    }
                    break;

                case Network.PacketTypes.DISCONNECT: //Someone has Disconnected
                    long thereID = message.ReadInt64();
                    if (PlayerStore.ContainsKey(thereID))
                    {
                        PlayerStore.Remove(thereID);
                    }
                    else
                    {
                        Console.WriteLine("Tried to remove non existant ID");
                    }

                    if (Program.Started)
                    {
                        load.Invoke(new Action(() => RefreshDisplay()));
                    }
                    break;
                case Network.PacketTypes.CHATREC: //Start the Game form.
                    long idrec = message.ReadInt64();
                    string recMessage = message.ReadString();
                    Console.WriteLine(idrec);
                    Console.WriteLine(recMessage);
                    Game.ChatMessages.Add(LoadScreen.RandomNumber(1, 99999999), new ChatMessage(PlayerStore[idrec], recMessage));
                    load.Invoke(new Action(() => load.RefreshChat()));

                    break;
            }
        }
        private void HandleJobList(NetIncomingMessage msg)
        {
            int byteNum = msg.ReadInt32();
            byte[] compressedXml = msg.ReadBytes(byteNum);

            string jobListXml = ZipString.UnZipStr(compressedXml);

            JobHandler.Singleton.LoadDefinitionsFromString(jobListXml);
            int pos = 5;
            _jobButtonContainer.components.Clear(); //Properly dispose old buttons !!!!!!!
            foreach (JobDefinition definition in JobHandler.Singleton.JobSettings.JobDefinitions)
            {
                var current = new JobSelectButton(definition.Name, definition.JobIcon, definition.Description,
                                                  ResourceManager)
                                  {
                                      Available = definition.Available,
                                      Position = new Point(5, pos)
                                  };

                current.Clicked += CurrentClicked;
                current.UserData = definition;
                _jobButtonContainer.components.Add(current);
                pos += current.ClientArea.Height + 20;
            }
        }
Exemple #27
0
        private void HandleJobList(NetIncomingMessage msg)
        {
            int byteNum = msg.ReadInt32();
            byte[] compressedXml = msg.ReadBytes(byteNum);

            string jobListXml = ZipString.UnZipStr(compressedXml);

            JobHandler.Singleton.LoadDefinitionsFromString(jobListXml);

            _tabJob._shwDepa.ClearItems();
            _tabJob._shwJobs.ClearItems();

            sortedJobs.Clear();

            foreach (DepartmentDefinition dep in JobHandler.Singleton.JobSettings.DepartmentDefinitions)
            {
                var depJobs = (from x in JobHandler.Singleton.JobSettings.JobDefinitions
                              where x.Department.ToLowerInvariant() == dep.Name.ToLowerInvariant()
                              where x.Available
                              orderby x.Name
                              select x).ToList();

                var newEntry = new KeyValuePair<DepartmentDefinition, List<JobDefinition>>(dep, depJobs);
                sortedJobs.Add(newEntry);

                var newDep = new ImageButton
                {
                    ImageNormal = dep.DepartmentIcon,
                };

                DepartmentInfo newInfo = new DepartmentInfo()
                    {
                        Department = dep,
                        JobDefs = depJobs
                    };

                _tabJob._shwDepa.AddItem(newDep, newInfo);
            }
        }
Exemple #28
0
        private void ProcessNetIncomingMessageData(NetIncomingMessage message, bool unconnected)
        {
            try
            {
                if (!unconnected)
                {
                    switch (message.SequenceChannel)
                    {
                        case 0: // Assume everything sent along channel 0 is encrypted
                            if (!message.Decrypt(_encryption))
                            {
                                Log.Critical("Unable to decrypt packet on Channel 0, please check the key that is being used.");
                            }
                            break;
                    }
                }

                //var data = Illisian.UnityUtil.Compression.ByteArrays.Decompress(message.ReadBytes(message.LengthBytes));
                var data = message.ReadBytes(message.LengthBytes);
                NetMessage _msg = new NetMessage();
                _msg.NetConnection = message.SenderConnection;
                _msg.Object = Illisian.UnityUtil.Serialise.Binary.ByteArrayToObject(data);
                _msg.SequenceChannel = message.SequenceChannel;
                _msg.UnconnectedMessage = unconnected;

                if (OnIncomingMessage != null)
                {
                    OnIncomingMessage(_msg);
                }
                else
                {
                    Log.Warn("Packets are being received but nothing is listening on the event hook");
                }
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Unable to Process Incoming Message :: Error Message: {0}", ex.Message));
            }
        }
Exemple #29
0
 /// <summary>
 /// Reads a full gamestate from a NetIncomingMessage
 /// </summary>
 /// <param name="message">NetIncomingMessage that contains the state data</param>
 /// <returns></returns>
 public static GameState ReadStateMessage(NetIncomingMessage message)
 {
     uint sequence = message.ReadUInt32();
     int length = message.ReadInt32();
     byte[] stateData = Decompress(message.ReadBytes(length));
     using (var stateStream = new MemoryStream(stateData))
         return (GameState) Serializer.Deserialize(stateStream);
 }
 protected static byte[] ReadByteBuffer(NetIncomingMessage msgIn)
 {
     return msgIn.ReadBytes(msgIn.ReadInt32());
 }
 /// <summary>
 /// Handles an incoming entity component message
 /// </summary>
 /// <param name="message">Raw network message</param>
 /// <returns>An IncomingEntityComponentMessage object</returns>
 public IncomingEntityComponentMessage HandleEntityComponentNetworkMessage(NetIncomingMessage message)
 {
     var componentFamily = (ComponentFamily) message.ReadByte();
     var messageParams = new List<object>();
     while (message.Position < message.LengthBits)
     {
         switch ((NetworkDataType) message.ReadByte())
         {
             case NetworkDataType.d_enum:
                 messageParams.Add(message.ReadInt32());
                 break;
             case NetworkDataType.d_bool:
                 messageParams.Add(message.ReadBoolean());
                 break;
             case NetworkDataType.d_byte:
                 messageParams.Add(message.ReadByte());
                 break;
             case NetworkDataType.d_sbyte:
                 messageParams.Add(message.ReadSByte());
                 break;
             case NetworkDataType.d_ushort:
                 messageParams.Add(message.ReadUInt16());
                 break;
             case NetworkDataType.d_short:
                 messageParams.Add(message.ReadInt16());
                 break;
             case NetworkDataType.d_int:
                 messageParams.Add(message.ReadInt32());
                 break;
             case NetworkDataType.d_uint:
                 messageParams.Add(message.ReadUInt32());
                 break;
             case NetworkDataType.d_ulong:
                 messageParams.Add(message.ReadUInt64());
                 break;
             case NetworkDataType.d_long:
                 messageParams.Add(message.ReadInt64());
                 break;
             case NetworkDataType.d_float:
                 messageParams.Add(message.ReadFloat());
                 break;
             case NetworkDataType.d_double:
                 messageParams.Add(message.ReadDouble());
                 break;
             case NetworkDataType.d_string:
                 messageParams.Add(message.ReadString());
                 break;
             case NetworkDataType.d_byteArray:
                 int length = message.ReadInt32();
                 messageParams.Add(message.ReadBytes(length));
                 break;
         }
     }
     return new IncomingEntityComponentMessage(componentFamily, messageParams);
 }