コード例 #1
0
    static void CreateNetworkReader(byte[] data)
    {
        //https://docs.unity3d.com/ScriptReference/Networking.NetworkReader.html
        NetworkReader networkReader = new NetworkReader(data);

        // The first two bytes in the buffer represent the size of the message. This is equal to the NetworkReader.Length
        // minus the size of the prefix.
        networkReader.ReadBytes(2);
        //short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]);

        // The message type added in NetworkWriter.StartMessage is to be read now. It is a short and so consists of
        // two bytes. It is the second two bytes on the buffer.
        byte[] readerMsgTypeData = networkReader.ReadBytes(2);
        short  readerMsgType     = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]);

        //Debug.Log("Message of type " + readerMsgType + " received");

        if (readerMsgType == MessageTypes.JoinRequest)
        {
            JoinRequestMessage message = new JoinRequestMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinRequest(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnswer)
        {
            JoinAnswerMessage message = new JoinAnswerMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnswer(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnnounce)
        {
            JoinAnnounceMessage message = new JoinAnnounceMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnnounce(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.Position)
        {
            PositionMessage message = new PositionMessage();
            message.Deserialize(networkReader);
            p2PController.ReceivePositionInformation(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AskConsent)
        {
            AskConsentMessage message = new AskConsentMessage();
            message.Deserialize(networkReader);
            p2PController.OnAskForConsentMsg(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AnswerConsent)
        {
            AnswerConsentMessage message = new AnswerConsentMessage();
            message.Deserialize(networkReader);
            P2PConsentManager.ReceiveAnswerConsent(message);
        }
        else if (readerMsgType == MessageTypes.ApplyConsent)
        {
            ApplyConsentMessage message = new ApplyConsentMessage();
            message.Deserialize(networkReader);
            p2PController.ApplyConsent(message);
        }
    }
コード例 #2
0
    private void OnReceivedData(IAsyncResult result)
    {
        try
        {
            int    length = stream.EndRead(result);
            byte[] data   = new byte[length];

            Buffer.BlockCopy(asyncBuffer, 0, data, 0, length);

            if (length <= 0)
            {
                Debug.Log("Disconnected from server.");
                Application.Quit();
                return;
            }

            NetworkReader networkReader = new NetworkReader(data);

            byte[] readerMsgSizeData = networkReader.ReadBytes(2);
            short  readerMsgSize     = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]);
            //Debug.Log(readerMsgSize);

            byte[] readerMsgTypeData = networkReader.ReadBytes(2);
            short  readerMsgType     = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]);
            //Debug.Log(readerMsgType);

            if (readerMsgType == MRTMsgType.Spawn)
            {
                SpawnMessage msg = new SpawnMessage();
                msg.Deserialize(networkReader);

                //Debug.Log(msg.connectId);
                //Debug.Log(msg.prefabId);
                Debug.Log(msg.position.ToString("F4"));
                Debug.Log(msg.payload);

                spawnManager.Spawn(msg);
            }
            else if (readerMsgType == MRTMsgType.Text)
            {
                TextMessage msg = new TextMessage();
                msg.Deserialize(networkReader);

                Debug.Log(msg.payload);

                //debugLog.Log(msg.payload);
            }

            stream.BeginRead(asyncBuffer, 0, asyncBuffer.Length, OnReceivedData, null);
        }
        catch (Exception)
        {
            Debug.Log("Disconnected from server.");
            Application.Quit();
            return;
        }
    }
コード例 #3
0
        public void ProcessUNetMessage(byte[] rawPacket)
        {
            var unetBytes = UNetMessage.Deserialize(rawPacket);

            var reader = new NetworkReader(unetBytes);

            while (reader.Position < unetBytes.Length)
            {
                var msg = new NetworkMessage();
                msg.msgSeqNum = reader.ReadUInt32();
                var msgSize = reader.ReadUInt16();
                msg.msgType = reader.ReadInt16();
                var buffer = reader.ReadBytes(msgSize);
                msg.reader = new NetworkReader(buffer);

                var deserialized = Deserialize(msg, buffer);

                if (deserialized != null)
                {
                    if (_handlers.ContainsKey(deserialized.msgType))
                    {
                        if (deserialized.GetType() != typeof(AssetsLoadingProgress))
                        {
                            Log.Print(LogType.Game, $"{deserialized.GetType().Name} - {JsonConvert.SerializeObject(deserialized)}");
                        }
                        _handlers[deserialized.msgType].Invoke(deserialized);
                    }
                    else
                    {
                        Log.Print(LogType.Warning,
                                  $"Unhandled {msg.msgType}:{deserialized.GetType().Name} - {JsonConvert.SerializeObject(deserialized)}");
                    }
                }
            }
        }
コード例 #4
0
        public override void Deserialize(int _senderID, byte[] _data, int _receivedBytes)
        {
            base.Deserialize(_senderID, _data, _receivedBytes);
            using (MemoryStream ms = new MemoryStream(_data, 0, _receivedBytes))
            {
                using (NetworkReader nr = new NetworkReader(ms))
                {
                    nr.ReadUInt16();
                    Position          = nr.ReadVector3();
                    Rotation          = nr.ReadQuaternion();
                    Scale             = nr.ReadVector3();
                    Prefab            = nr.ReadPrefab();
                    Parent            = nr.ReadTransform();
                    NetID             = nr.ReadUInt32();
                    IsLocalPlayer     = nr.ReadBoolean();
                    NetworkBehaviours = new byte[nr.ReadInt32()][];

                    int byteLength;
                    for (int i = 0; i < NetworkBehaviours.Length; i++)
                    {
                        byteLength           = nr.ReadInt32();
                        NetworkBehaviours[i] = nr.ReadBytes(byteLength);
                    }
                }
            }
        }
コード例 #5
0
        public byte[] Payload()
        {
            var reader = new NetworkReader(_data.ToArray());
            var bytes  = reader.ReadBytes(_size);

            return(bytes);
        }
コード例 #6
0
ファイル: NetworkWriterTest.cs プロジェクト: HeadClot/Mirage
        public void TestReading0LengthBytes()
        {
            writer.WriteBytes(new byte[] { }, 0, 0);
            var reader = new NetworkReader(writer.ToArray());

            Assert.That(reader.ReadBytes(0).Length, Is.EqualTo(0));
        }
コード例 #7
0
        public void TestWritingAndReading()
        {
            // write all simple types once
            NetworkWriter writer = new NetworkWriter();

            writer.Write((char)1);
            writer.Write((byte)2);
            writer.Write((sbyte)3);
            writer.Write((bool)true);
            writer.Write((short)4);
            writer.Write((ushort)5);
            writer.Write((int)6);
            writer.Write((uint)7);
            writer.Write((long)8L);
            writer.Write((ulong)9L);
            writer.Write((float)10);
            writer.Write((double)11);
            writer.Write((decimal)12);
            writer.Write((string)null);
            writer.Write((string)"");
            writer.Write((string)"13");
            writer.Write(new byte[] { 14, 15 }, 0, 2);                 // just the byte array, no size info etc.
            writer.WriteBytesAndSize((byte[])null);                    // [SyncVar] struct values can have uninitialized byte arrays, null needs to be supported
            writer.WriteBytesAndSize(new byte[] { 17, 18 }, 0, 2);     // buffer, no-offset, count
            writer.WriteBytesAndSize(new byte[] { 19, 20, 21 }, 1, 2); // buffer, offset, count
            writer.WriteBytesAndSize(new byte[] { 22, 23 }, 0, 2);     // size, buffer

            byte[] data = writer.ToArray();


            // read them
            NetworkReader reader = new NetworkReader(writer.ToArray());

            Assert.That(reader.ReadChar(), Is.EqualTo(1));
            Assert.That(reader.ReadByte(), Is.EqualTo(2));
            Assert.That(reader.ReadSByte(), Is.EqualTo(3));
            Assert.That(reader.ReadBoolean(), Is.True);
            Assert.That(reader.ReadInt16(), Is.EqualTo(4));
            Assert.That(reader.ReadUInt16(), Is.EqualTo(5));
            Assert.That(reader.ReadInt32(), Is.EqualTo(6));
            Assert.That(reader.ReadUInt32(), Is.EqualTo(7));
            Assert.That(reader.ReadInt64(), Is.EqualTo(8));
            Assert.That(reader.ReadUInt64(), Is.EqualTo(9));
            Assert.That(reader.ReadSingle(), Is.EqualTo(10));
            Assert.That(reader.ReadDouble(), Is.EqualTo(11));
            Assert.That(reader.ReadDecimal(), Is.EqualTo(12));
            Assert.That(reader.ReadString(), Is.Null); // writing null string should write null in HLAPI Pro ("" in original HLAPI)
            Assert.That(reader.ReadString(), Is.EqualTo(""));
            Assert.That(reader.ReadString(), Is.EqualTo("13"));

            Assert.That(reader.ReadBytes(2), Is.EqualTo(new byte[] { 14, 15 }));

            Assert.That(reader.ReadBytesAndSize(), Is.Null);

            Assert.That(reader.ReadBytesAndSize(), Is.EqualTo(new byte[] { 17, 18 }));

            Assert.That(reader.ReadBytesAndSize(), Is.EqualTo(new byte[] { 20, 21 }));

            Assert.That(reader.ReadBytesAndSize(), Is.EqualTo(new byte[] { 22, 23 }));
        }
コード例 #8
0
    public override void Deserialize(NetworkReader reader)
    {
        base.Deserialize(reader);
        SteamID = reader.ReadUInt64();
        int length = reader.ReadInt32();

        TicketBinary = reader.ReadBytes(length);
    }
コード例 #9
0
        protected override MyStruct DeserializeItem(NetworkReader reader)
        {
            MyStruct ret;
            uint     sz = reader.ReadPackedUInt32();

            ret.data  = reader.ReadBytes((int)sz);
            ret.seqId = reader.ReadInt32();
            return(ret);
        }
コード例 #10
0
        public static byte[] ReadBytesAndSize(this NetworkReader reader)
        {
            // count = 0 means the array was null
            // otherwise count -1 is the length of the array
            uint count = reader.ReadUInt();

            // Use checked() to force it to throw OverflowException if data is invalid
            return(count == 0 ? null : reader.ReadBytes(checked ((int)(count - 1u))));
        }
コード例 #11
0
        public override void Deserialize(NetworkReader reader)
        {
            var type = typeof(TData);

            Data = (TData)Activator.CreateInstance(type);

            var data = new MemoryStream(reader.ReadBytes(reader.Length));

            Data.Deserialize(new BinaryReader(data));
        }
コード例 #12
0
    new protected void HandleReader(
        NetworkReader reader,
        int receivedSize,
        int channelId)
    {
        // read until size is reached.
        // NOTE: stream.Capacity is 1300, NOT the size of the available data
        while (reader.Position < receivedSize)
        {
            // the reader passed to user code has a copy of bytes from the real stream. user code never touches the real stream.
            // this ensures it can never get out of sync if user code reads less or more than the real amount.
            ushort sz      = reader.ReadUInt16();
            short  msgType = reader.ReadInt16();

            // create a reader just for this message
            byte[]        msgBuffer = reader.ReadBytes(sz);
            NetworkReader msgReader = new NetworkReader(msgBuffer);

            if (logNetworkMessages)
            {
                StringBuilder msg = new StringBuilder();
                for (int i = 0; i < sz; i++)
                {
                    msg.AppendFormat("{0:X2}", msgBuffer[i]);
//					if (i > k_MaxMessageLogSize) break;
                }
                Debug.Log("ConnectionRecv con:" + connectionId + " bytes:" + sz + " msgId:" + msgType + " " + msg);
            }

            NetworkMessageDelegate msgDelegate = null;
            if (m_MessageHandlersDict.ContainsKey(msgType))
            {
                msgDelegate = m_MessageHandlersDict[msgType];
            }
            if (msgDelegate != null)
            {
                m_NetMsg.msgType   = msgType;
                m_NetMsg.reader    = msgReader;
                m_NetMsg.conn      = this;
                m_NetMsg.channelId = channelId;
                msgDelegate(m_NetMsg);
                lastMessageTime = Time.time;
            }
            else
            {
                //NOTE: this throws away the rest of the buffer. Need moar error codes
                if (LogFilter.logError)
                {
                    Debug.LogError("Unknown message ID " + msgType + " connId:" + connectionId);
                }
                break;
            }
        }
    }
コード例 #13
0
        public void ReadUpdatedNetVars(NetworkReader reader, bool[] updatedNetVars, int currentPosition, bool force, float sendRate)
        {
            if (observed == null) //We need to be reading regardless of whether we are observed/ enabled.
            {
                return;
            }

            if (force || updatedNetVars[currentPosition])
            {
                if (force)
                {
                    observed.velocity    = reader.ReadBytes(3).ByteArrayToVector3() * maxVelocity;
                    lastReceivedVelocity = observed.velocity;
                }
                else
                {
                    lastReceivedVelocity += reader.ReadBytes(3).ByteArrayToVector3() * maxVelocity;
                    observed.velocity     = lastReceivedVelocity;
                }
            }
        }
コード例 #14
0
            public static ReePacketPayload Deserialize(NetworkReader reader)
            {
                ReePacketPayload rpp = new ReePacketPayload();

                rpp.DataLength = reader.ReadInt32();
                byte[] restOfBytes  = reader.ReadBytes(rpp.DataLength);
                var    mStream      = new MemoryStream(restOfBytes);
                var    binFormatter = new BinaryFormatter();

                rpp.PayloadData = (List <object>)binFormatter.Deserialize(mStream);
                return(rpp);
            }
        public override void Deserialize(NetworkReader reader)
        {
            ImageTargetIndex = reader.ReadInt32();
            StepOrder        = reader.ReadUInt32();

            var application = Object.FindObjectOfType <Base.Application>();

            Data = Object.Instantiate(application.Prefabs.StepModelPrefab);
            var data = new MemoryStream(reader.ReadBytes(reader.Length - 8));

            Data.Deserialize(new BinaryReader(data));
        }
コード例 #16
0
ファイル: Network.cs プロジェクト: Reinms/RoR2Modding
        private static void HandleReplyServer(NetworkMessage msg)
        {
            NetworkReader reader = msg.reader;
            Header        header = reader.ReadNew <Header>();

            if (header.destination.ShouldRun())
            {
                header.RemoveDestination(NetworkDestination.Server);

                if (netMessages.TryGetValue(header.typeCode, out INetMessage message))
                {
                    message.Deserialize(reader);
                    message.OnRecieved();
                }
                else
                {
                    Log.Error("Unhandled message recieved, you may be missing mods");
                }
            }

            if (header.destination.ShouldSend())
            {
                Int32  recievedFrom = msg.conn.connectionId;
                Byte[] bytes        = reader.ReadBytes((Int32)(reader.Length - reader.Position));
                for (Int32 i = 0; i < NetworkServer.connections.Count; ++i)
                {
                    if (i == recievedFrom)
                    {
                        continue;
                    }

                    NetworkConnection conn = NetworkServer.connections[i];
                    if (conn == null)
                    {
                        continue;
                    }


                    if (NetworkServer.localClientActive && NetworkServer.localConnections.Contains(conn))
                    {
                        continue;
                    }

                    using (Writer netWriter = GetWriter(messageIndex, conn, qos))
                    {
                        NetworkWriter writer = netWriter;
                        writer.Write(header);
                        writer.WriteBytesFull(bytes);
                    }
                }
            }
        }
コード例 #17
0
    void CreateNetworkReader(byte[] data)
    {
        // We will create the NetworkReader using the data from our previous
        // NetworkWriter.
        NetworkReader networkReader = new NetworkReader(data);


        // The first two bytes in the buffer represent the size
        // of the message. This is equal to the NetworkReader.Length
        // minus the size of the prefix.
        byte[] readerMsgSizeData = networkReader.ReadBytes(2);
        short  readerMsgSize     = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]);

        Debug.Log(readerMsgSize);


        // The message type added in NetworkWriter.StartMessage
        // is to be read now. It is a short and so consists of
        // two bytes. It is the second two bytes on the buffer.
        byte[] readerMsgTypeData = networkReader.ReadBytes(2);
        short  readerMsgType     = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]);

        Debug.Log(readerMsgType);

        // If all of your data is of the same type (in this case the
        // data on our buffer is comprised of only strings) you can
        // read all the data from the buffer using a loop like so.
        while (networkReader.Position < networkReader.Length)
        {
            Debug.Log(networkReader.ReadString());
        }

        Debug.Log("MsgType.Connect " + MsgType.Connect);
        Debug.Log("MsgType.Error " + MsgType.Error);
        Debug.Log("MsgType.NetworkInfo " + MsgType.NetworkInfo);
        Debug.Log("MsgType.ObjectSpawn " + MsgType.ObjectSpawn);
        Debug.Log("MsgType.ObjectSpawnScene " + MsgType.ObjectSpawnScene);
        Debug.Log("MsgType.SpawnFinished " + MsgType.SpawnFinished);
    }
コード例 #18
0
        public static AnimatorUpdate ReadAnimatorUpdate(this NetworkReader reader)
        {
            AnimatorUpdate au = new AnimatorUpdate();

            //Component index.
            au.ComponentIndex = reader.ReadByte();

            //Network identity.
            byte netIdCompression = reader.ReadByte();

            if (netIdCompression == 1)
            {
                au.NetworkIdentity = reader.ReadByte();
            }
            else if (netIdCompression == 2)
            {
                au.NetworkIdentity = reader.ReadUInt16();
            }
            else
            {
                au.NetworkIdentity = reader.ReadUInt32();
            }

            //Animation data.
            byte dataLengthCompression = reader.ReadByte();
            int  dataLength;

            if (dataLengthCompression == 1)
            {
                dataLength = reader.ReadByte();
            }
            else if (dataLengthCompression == 2)
            {
                dataLength = reader.ReadUInt16();
            }
            else
            {
                dataLength = reader.ReadInt32();
            }

            if (dataLength > 0)
            {
                au.Data = reader.ReadBytes(dataLength);
            }
            else
            {
                au.Data = new byte[0];
            }

            return(au);
        }
コード例 #19
0
 public override void Deserialize(int _senderID, byte[] _data, int _receivedBytes)
 {
     base.Deserialize(_senderID, _data, _receivedBytes);
     using (MemoryStream ms = new MemoryStream(_data, 0, _receivedBytes))
     {
         using (NetworkReader nr = new NetworkReader(ms))
         {
             nr.ReadUInt16();
             NetID       = nr.ReadNetworkIdentity();
             ComponentID = nr.ReadUInt32();
             int length = nr.ReadInt32();
             Bytes = nr.ReadBytes(length);
         }
     }
 }
コード例 #20
0
        public override void Deserialize(NetworkReader reader)
        {
            id        = reader.ReadString();
            timeStamp = reader.ReadSingle();

            int objNum = reader.ReadInt32();

            objects = objNum == 0 ? null : new object[objNum];

            for (int i = 0; i < objNum; i++)
            {
                short  len   = reader.ReadInt16();
                byte[] bytes = reader.ReadBytes(len);
                objects[i] = ByteArrayToObject(bytes);
            }
        }
コード例 #21
0
        public static List <ObjectData> GetRecording(string fileName, ref uint tickCount, ref float tickTime, ref uint version, GameObject playerPrefab)
        {
            NetworkReader reader = new NetworkReader(File.ReadAllBytes(fileName));

            List <ObjectData> ret = new List <ObjectData> ();

            version = reader.ReadPackedUInt32();

            tickTime = reader.ReadSingle();
            uint cnt = reader.ReadPackedUInt32();

            for (int i = 0; i < cnt; i++)
            {
                uint       goIndex = reader.ReadPackedUInt32();
                GameObject obj     = GameObject.Instantiate(settings.recordGameObjects[(int)goIndex]);

                if (obj.GetComponent <RecordableObject> () != null)
                {
                    obj.GetComponent <RecordableObject> ().SetPlayback();
                    ret.Add(new ObjectData(obj.GetComponent <RecordableObject> (), goIndex, reader.ReadPackedUInt32()));
                    ret [i].endTick = reader.ReadPackedUInt32();
                    if (tickCount < ret [i].endTick)
                    {
                        tickCount = ret [i].endTick;
                    }
                    //The placeholder for init properties buffer length
                    reader.ReadPackedUInt32();
                    uint cnt2 = reader.ReadPackedUInt32();
                    ret [i].ticks = new List <RecordData> ();
                    for (int o = 0; o < cnt2; o++)
                    {
                        int    s         = reader.ReadInt32();
                        byte[] bytes     = reader.ReadBytes(s);
                        uint   timestamp = reader.ReadPackedUInt32();
                        ret [i].ticks.Add(new RecordData(bytes, timestamp));
                    }
                }
                else
                {
                    Debug.LogError("No RecordableObject component found on: " + obj);
                    Destroy(obj);
                }
            }

            return(ret);
        }
コード例 #22
0
        //
        // Client Update Loop
        //

        public void Client_ReceiveGameObjectUpdate(NetworkReader reader)
        {
            lastReceivedTime = Time.time;

            // Read the bool array with what has been updated.
            bool[] updatedNetVars = reader.ReadBytes(NumNetVars.BoolArraySizeToByteArraySize()).ToBoolArray();

            //Debug.Log(string.Join(", ", updatedNetVars.Select(x => x.ToString()).ToArray()));

            int currentPosition = 0;

            for (int i = 0; i < activeNetworkComponents.Count; i++)
            {
                activeNetworkComponents[i].ReadUpdatedNetVars(reader, updatedNetVars, currentPosition, false, 1f / updatesPerSecond);
                currentPosition += activeNetworkComponents[i].NumNetVars;
            }
        }
コード例 #23
0
        public void ProcessUNetMessages(byte[] rawPacket)
        {
            var unetBytes = UNetMessage.Deserialize(rawPacket);

            var reader = new NetworkReader(unetBytes);

            while (reader.Position < unetBytes.Length)
            {
                var msg = new NetworkMessage();
                msg.msgSeqNum = reader.ReadUInt32();
                var msgSize = reader.ReadUInt16();
                msg.msgType = reader.ReadInt16();
                var buffer = reader.ReadBytes(msgSize);
                msg.reader = new NetworkReader(buffer);

                ProcessUnetMessage(msg);
            }
        }
コード例 #24
0
        public void ReadBytesCountTooBigTest()
        {
            // calling ReadBytes with a count bigger than what is in Reader
            // should throw an exception
            byte[]        bytes  = { 0x00, 0x01 };
            NetworkReader reader = new NetworkReader(bytes);

            try
            {
                byte[] result = reader.ReadBytes(bytes, bytes.Length + 1);
                // BAD: IF WE GOT HERE, THEN NO EXCEPTION WAS THROWN
                Assert.Fail();
            }
            catch (EndOfStreamException)
            {
                // GOOD
            }
        }
コード例 #25
0
        public void ReadUpdatedNetVars(NetworkReader reader, bool[] updatedNetVars, int currentPosition, bool forceUpdate, float sendRate)
        {
            if (observed == null) //We need to be reading regardless of whether we are observed/ enabled.
            {
                return;
            }

            if (forceUpdate || updatedNetVars[currentPosition])
            {
                if (forceUpdate)
                {
                    observed.position    = reader.ReadVector3();
                    lastReceivedPosition = observed.position;
                }
                else
                {
                    lastReceivedPosition += reader.ReadBytes(3).ByteArrayToVector3() * maxDistance;
                    observed.DOMove(lastReceivedPosition, sendRate * positionInterpolationScale).SetEase(Ease.Linear);
                }
            }

            if (forceUpdate || updatedNetVars[currentPosition + 1])
            {
                lastReceivedAngle = reader.ReadByte().ZeroOneToFloat() * 360;
                if (forceUpdate)
                {
                    observed.eulerAngles = new Vector3(0, lastReceivedAngle, 0);
                }
                else
                {
                    observed.DORotate(new Vector3(0, lastReceivedAngle, 0), sendRate * rotationInterpolationScale);
                }
            }

            lastReceivedTime = Time.time;
        }
コード例 #26
0
ファイル: UnknownRpc.cs プロジェクト: LimitlessRegret/EvoS
 public override void Deserialize(NetworkReader reader, GameObject context)
 {
     Payload = reader.ReadBytes((int)(reader.Length - reader.Position));
 }
コード例 #27
0
 /// <summary>
 ///   <para>This makes the connection process the data contained in the stream, and call handler functions.</para>
 /// </summary>
 /// <param name="reader">Stream that contains data.</param>
 /// <param name="receivedSize">Size of the data.</param>
 /// <param name="channelId">Channel the data was received on.</param>
 protected void HandleReader(NetworkReader reader, int receivedSize, int channelId)
 {
   while ((long) reader.Position < (long) receivedSize)
   {
     ushort num = reader.ReadUInt16();
     short key = reader.ReadInt16();
     byte[] buffer = reader.ReadBytes((int) num);
     NetworkReader networkReader = new NetworkReader(buffer);
     if (this.logNetworkMessages)
     {
       StringBuilder stringBuilder = new StringBuilder();
       for (int index = 0; index < (int) num; ++index)
       {
         stringBuilder.AppendFormat("{0:X2}", (object) buffer[index]);
         if (index > 150)
           break;
       }
       Debug.Log((object) ("ConnectionRecv con:" + (object) this.connectionId + " bytes:" + (object) num + " msgId:" + (object) key + " " + (object) stringBuilder));
     }
     NetworkMessageDelegate networkMessageDelegate = (NetworkMessageDelegate) null;
     if (this.m_MessageHandlersDict.ContainsKey(key))
       networkMessageDelegate = this.m_MessageHandlersDict[key];
     if (networkMessageDelegate != null)
     {
       this.m_NetMsg.msgType = key;
       this.m_NetMsg.reader = networkReader;
       this.m_NetMsg.conn = this;
       this.m_NetMsg.channelId = channelId;
       networkMessageDelegate(this.m_NetMsg);
       this.lastMessageTime = Time.time;
       NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short) 28, "msg", 1);
       if ((int) key > 47)
         NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short) 0, key.ToString() + ":" + key.GetType().Name, 1);
       if (this.m_PacketStats.ContainsKey(key))
       {
         NetworkConnection.PacketStat packetStat = this.m_PacketStats[key];
         ++packetStat.count;
         packetStat.bytes += (int) num;
       }
       else
       {
         NetworkConnection.PacketStat packetStat = new NetworkConnection.PacketStat();
         packetStat.msgType = key;
         ++packetStat.count;
         packetStat.bytes += (int) num;
         this.m_PacketStats[key] = packetStat;
       }
     }
     else
     {
       if (!LogFilter.logError)
         break;
       Debug.LogError((object) ("Unknown message ID " + (object) key + " connId:" + (object) this.connectionId));
       break;
     }
   }
 }
コード例 #28
0
 internal void HandleMessage(Dictionary<short, NetworkMessageDelegate> handler, NetworkReader reader, int receivedSize, int channelId)
 {
     while ((long) reader.Position < (long) receivedSize)
       {
     ushort num = reader.ReadUInt16();
     short key = reader.ReadInt16();
     NetworkReader networkReader = new NetworkReader(reader.ReadBytes((int) num));
     NetworkMessageDelegate networkMessageDelegate = (NetworkMessageDelegate) null;
     if (handler.ContainsKey(key))
       networkMessageDelegate = handler[key];
     if (networkMessageDelegate != null)
     {
       this.m_netMsg.msgType = key;
       this.m_netMsg.reader = networkReader;
       this.m_netMsg.conn = this;
       this.m_netMsg.channelId = channelId;
       networkMessageDelegate(this.m_netMsg);
       NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short) 28, "msg", 1);
       if ((int) key > 46)
     NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short) 0, key.ToString() + ":" + key.GetType().Name, 1);
       if (this.m_PacketStats.ContainsKey(key))
       {
     NetworkConnection.PacketStat packetStat = this.m_PacketStats[key];
     ++packetStat.count;
     packetStat.bytes += (int) num;
       }
       else
       {
     NetworkConnection.PacketStat packetStat = new NetworkConnection.PacketStat();
     packetStat.msgType = key;
     ++packetStat.count;
     packetStat.bytes += (int) num;
     this.m_PacketStats[key] = packetStat;
       }
     }
     else
     {
       if (!LogFilter.logError)
     break;
       Debug.LogError((object) ("Unknown message ID " + (object) key));
       break;
     }
       }
 }
コード例 #29
0
ファイル: NetworkWriterTest.cs プロジェクト: MirageNet/Mirage
 public void TestReading0LengthBytes()
 {
     writer.WriteBytes(new byte[] { }, 0, 0);
     reader.Reset(writer.ToArraySegment());
     Assert.That(reader.ReadBytes(0).Length, Is.EqualTo(0));
 }
コード例 #30
0
 public override void Deserialize(NetworkReader reader)
 {
     NetId   = reader.ReadNetworkId();
     Hash    = (int)reader.ReadPackedUInt32();
     Payload = reader.ReadBytes((int)(reader.Length - reader.Position));
 }
コード例 #31
0
 private void ReturnReaderTo(uint position, NetworkReader reader)
 {
     reader.SeekZero();
     reader.ReadBytes((int)position);
 }
コード例 #32
0
 public static Guid ReadGuid(this NetworkReader reader)
 {
     return(new Guid(reader.ReadBytes(16)));
 }
コード例 #33
0
 /// <summary>
 /// <para>This makes the connection process the data contained in the stream, and call handler functions.</para>
 /// </summary>
 /// <param name="reader">Stream that contains data.</param>
 /// <param name="receivedSize">Size of the data.</param>
 /// <param name="channelId">Channel the data was received on.</param>
 protected void HandleReader(NetworkReader reader, int receivedSize, int channelId)
 {
     while (reader.Position < receivedSize)
     {
         ushort count = reader.ReadUInt16();
         short key = reader.ReadInt16();
         byte[] buffer = reader.ReadBytes(count);
         NetworkReader reader2 = new NetworkReader(buffer);
         if (this.logNetworkMessages)
         {
             StringBuilder builder = new StringBuilder();
             for (int i = 0; i < count; i++)
             {
                 builder.AppendFormat("{0:X2}", buffer[i]);
                 if (i > 150)
                 {
                     break;
                 }
             }
             Debug.Log(string.Concat(new object[] { "ConnectionRecv con:", this.connectionId, " bytes:", count, " msgId:", key, " ", builder }));
         }
         NetworkMessageDelegate delegate2 = null;
         if (this.m_MessageHandlersDict.ContainsKey(key))
         {
             delegate2 = this.m_MessageHandlersDict[key];
         }
         if (delegate2 != null)
         {
             this.m_NetMsg.msgType = key;
             this.m_NetMsg.reader = reader2;
             this.m_NetMsg.conn = this;
             this.m_NetMsg.channelId = channelId;
             delegate2(this.m_NetMsg);
             this.lastMessageTime = Time.time;
             NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, 0x1c, "msg", 1);
             if (key > 0x2f)
             {
                 NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, 0, key.ToString() + ":" + key.GetType().Name, 1);
             }
             if (this.m_PacketStats.ContainsKey(key))
             {
                 PacketStat stat = this.m_PacketStats[key];
                 stat.count++;
                 stat.bytes += count;
             }
             else
             {
                 PacketStat stat2 = new PacketStat {
                     msgType = key
                 };
                 stat2.count++;
                 stat2.bytes += count;
                 this.m_PacketStats[key] = stat2;
             }
         }
         else
         {
             if (LogFilter.logError)
             {
                 Debug.LogError(string.Concat(new object[] { "Unknown message ID ", key, " connId:", this.connectionId }));
             }
             break;
         }
     }
 }