Exemplo n.º 1
0
        public IEnumerator ServerAndClient_PingPong_Successfully()
        {
            SetupServerAndClientAndConnectThem(0);

            //send data from client
            DataStreamWriter m_OutStream = new DataStreamWriter(16, Allocator.Persistent);

            m_OutStream.Clear();
            m_OutStream.Write(SharedConstants.ping);
            clientToServerConnection.Send(client_driver, m_OutStream);

            //handle sent data
            server_driver.ScheduleUpdate().Complete();
            ev = server_driver.PopEventForConnection(connectionToClient, out stream);
            Assert.IsTrue(ev == NetworkEvent.Type.Data, "Expected to get Type.Data");
            var readerCtx = default(DataStreamReader.Context);
            var msg       = stream.ReadBytesAsArray(ref readerCtx, stream.Length);

            if (msg.Length == SharedConstants.ping.Length)
            {
                for (var i = 0; i < msg.Length; i++)
                {
                    if (SharedConstants.ping[i] != msg[i])
                    {
                        Assert.Fail("Data reading error");
                    }
                }
            }

            client_driver.ScheduleUpdate().Complete();

            //send data from server
            m_OutStream.Clear();
            m_OutStream.Write(SharedConstants.pong);
            connectionToClient.Send(server_driver, m_OutStream);
            m_OutStream.Dispose();

            //handle sent data
            server_driver.ScheduleUpdate().Complete();
            client_driver.ScheduleUpdate().Complete();
            ev = clientToServerConnection.PopEvent(client_driver, out stream);
            Assert.IsTrue(ev == NetworkEvent.Type.Data, "Expected to get Type.Data");
            readerCtx = default(DataStreamReader.Context);
            msg       = stream.ReadBytesAsArray(ref readerCtx, stream.Length);
            if (msg.Length == SharedConstants.pong.Length)
            {
                for (var i = 0; i < msg.Length; i++)
                {
                    if (SharedConstants.pong[i] != msg[i])
                    {
                        Assert.Fail("Data reading error");
                    }
                }
            }

            DisconnectAndCleanup();
            yield return(null);
        }
Exemplo n.º 2
0
    private void ProcessCommandReceived(DataStreamReader stream)
    {
        var readerCtx = default(DataStreamReader.Context);

        Server.Command.Type commandType = (Server.Command.Type)stream.ReadUInt(ref readerCtx);

        switch (commandType)
        {
        case Server.Command.Type.KEEP_ALIVE:
            //VisualLog.instance.log("Received " + commandType.ToString() + " from Server");
            break;

        case Server.Command.Type.CUSTOM_MESSAGE:
            string message = Encoding.UTF8.GetString(stream.ReadBytesAsArray(ref readerCtx, stream.Length - 4));
            VisualLog.instance.log("Received " + commandType.ToString() + " from Server. Message: " + message);
            break;

        case Server.Command.Type.POSITION:
            float   x        = stream.ReadFloat(ref readerCtx);
            float   y        = stream.ReadFloat(ref readerCtx);
            float   z        = stream.ReadFloat(ref readerCtx);
            Vector3 position = new Vector3(x, y, z);
            VisualLog.instance.log("Received " + commandType.ToString() + " from Server. Position: " + position);
            break;

        default:
            break;
        }
    }
Exemplo n.º 3
0
        public override void Read(DataStreamReader reader, ref DataStreamReader.Context context)
        {
            if (Data == null)
            {
                Data = new SpawnRPCData();
            }

            Data.InstanceId = reader.ReadInt(ref context);
            Data.PrefabId   = reader.ReadInt(ref context);
            Data.Ownership  = (EOwnershipType)reader.ReadInt(ref context);

            byte[]  buff     = reader.ReadBytesAsArray(ref context, sizeof(float) * 7);
            Vector3 position = Vector3.zero;

            position.x = BitConverter.ToSingle(buff, 0 * sizeof(float));
            position.y = BitConverter.ToSingle(buff, 1 * sizeof(float));
            position.z = BitConverter.ToSingle(buff, 2 * sizeof(float));

            var rotation = Quaternion.identity;

            rotation.x = BitConverter.ToSingle(buff, 3 * sizeof(float));
            rotation.y = BitConverter.ToSingle(buff, 4 * sizeof(float));
            rotation.z = BitConverter.ToSingle(buff, 5 * sizeof(float));
            rotation.w = BitConverter.ToSingle(buff, 6 * sizeof(float));

            Data.Position = position;
            Data.Rotation = rotation;
        }
    public override void Read(int connectionId, DataStreamReader stream, ref DataStreamReader.Context context)
    {
        var bytesLength = stream.ReadInt(ref context);
        var bytes       = stream.ReadBytesAsArray(ref context, bytesLength);
        var text        = Encoding.ASCII.GetString(bytes);

        if (text.Length > 0)
        {
            if (Label.text.Length > 0)
            {
                Label.text += "\n";
            }

            Label.text += $"{connectionId} says: {text}";
        }

        // This means you're the server.
        if (Server != null)
        {
            var writer = new DataStreamWriter(bytes.Length + 8, Allocator.Temp);

            writer.Write(Id);
            writer.Write(bytes.Length);
            writer.Write(bytes);

            Server.WriteToAllConnections(writer);
        }
    }
    private void ProcessCommandReceived(NetworkConnection connection, DataStreamReader stream)
    {
        var readerCtx = default(DataStreamReader.Context);

        Client.Command.Type commandType = (Client.Command.Type)stream.ReadUInt(ref readerCtx);

        switch (commandType)
        {
        case Client.Command.Type.KEEP_ALIVE:
            //VisualLog.instance.log("Received " + commandType.ToString() + " from Client " + connection.InternalId.ToString() + ", Hash: " + connection.GetHashCode());
            SendCommand(new Command(Command.Type.KEEP_ALIVE, 0, connection.InternalId));
            break;

        case Client.Command.Type.CUSTOM_MESSAGE:
            string message = Encoding.UTF8.GetString(stream.ReadBytesAsArray(ref readerCtx, stream.Length - 4));
            VisualLog.instance.log("Received " + commandType.ToString() + " from Client " + connection.InternalId.ToString() + ", Hash: " + connection.GetHashCode() + ". Message: " + message);
            break;

        case Client.Command.Type.POSITION:
            float   x        = stream.ReadFloat(ref readerCtx);
            float   y        = stream.ReadFloat(ref readerCtx);
            float   z        = stream.ReadFloat(ref readerCtx);
            Vector3 position = new Vector3(x, y, z);
            VisualLog.instance.log("Received " + commandType.ToString() + " from Client " + connection.InternalId.ToString() + ", Hash: " + connection.GetHashCode() + ". Position: " + position);
            break;

        default:
            break;
        }
    }
Exemplo n.º 6
0
        /// <summary>
        /// Parses data from streamReader into a byte array for processing.
        /// </summary>
        public static void parse(DataStreamReader streamReader)
        {
            //Tracks where in the data stream you are and how much you've read
            var readerContext = default(DataStreamReader.Context);

            //Attempt to read Message byte array from streamReader
            byte[] msgBytes = streamReader.ReadBytesAsArray(ref readerContext, streamReader.Length);

            processMessage(msgBytes); //Process the message data
        }
        public override void Read(DataStreamReader reader, ref DataStreamReader.Context context)
        {
            byte[]  buff     = reader.ReadBytesAsArray(ref context, sizeof(float) * 7);
            Vector3 position = Vector3.zero;

            position.x = BitConverter.ToSingle(buff, 0 * sizeof(float));
            position.y = BitConverter.ToSingle(buff, 1 * sizeof(float));
            position.z = BitConverter.ToSingle(buff, 2 * sizeof(float));

            var rotation = Quaternion.identity;

            rotation.x = BitConverter.ToSingle(buff, 3 * sizeof(float));
            rotation.y = BitConverter.ToSingle(buff, 4 * sizeof(float));
            rotation.z = BitConverter.ToSingle(buff, 5 * sizeof(float));
            rotation.w = BitConverter.ToSingle(buff, 6 * sizeof(float));

            var distance = Vector3.Distance(Data.Target.position, position);

            // the further you are, the slower?

            Data.Target.rotation = rotation;

            if (_currentPosition == null)
            {
                _currentPosition = position;
            }
            else
            {
                var dist = Vector3.Distance(_currentPosition.Value, position);

                if (dist > 0.01f)
                {
                    var newPosition  = position;
                    var lastPosition = _currentPosition;
                    var dir          = newPosition - lastPosition;

                    _currentPosition = position;

                    var predictedPosition = newPosition + dir * 1.1F;
                    position = predictedPosition.Value;
                }
                else
                {
                    position = _currentPosition.Value;
                }
            }

            _targetPosition = position;

            //Debug.Log($"Read: {Data}");
        }
Exemplo n.º 8
0
    public async Task StartHost()
    {
        if (isStarted)
        {
            return;
        }

        isStarted = true;
        isHost    = true;

        var endpoint = new IPEndPoint(IPAddress.Broadcast, broadcastPort);

        client = new UdpClient();
        client.Connect(endpoint);
        Debug.Log("Broadcast StartHost");

        unsafe {
            int strByteCount = DataStreamWriter.GetByteSizeStr(m_broadcastData);
            using (var writer = new DataStreamWriter(10 + strByteCount, Allocator.Temp)) {
                writer.Write(m_broadcastKey);
                writer.Write(m_broadcastVersion);
                writer.Write(m_broadcastData);

                var reader = new DataStreamReader(writer, 0, writer.Length);
                var ctx    = default(DataStreamReader.Context);
                discovetyPacket = reader.ReadBytesAsArray(ref ctx, writer.Length);
            }
        }

        while (true)
        {
            if (isStarted)
            {
                await Task.Delay((int)(1000 * m_broadcastInterval));

                await client.SendAsync(discovetyPacket, discovetyPacket.Length);

                //Debug.Log ("Broadcast SendAsync");
            }
            else
            {
                break;
            }
        }

        if (client != null)
        {
            client.Close();
            client = null;
        }
    }
        public unsafe void Assert_GotDataRequest(NetworkEndPoint from, byte[] dataToCompare)
        {
            NetworkEndPoint remote = default(NetworkEndPoint);

            m_LocalDataStream.Clear();
            network_iovec[] iovecs = new network_iovec[2];
            iovecs[0].buf = m_LocalDataStream.GetUnsafePtr();
            iovecs[0].len = sizeof(UdpCHeader);
            iovecs[1].buf = m_LocalDataStream.GetUnsafePtr() + sizeof(UdpCHeader);
            iovecs[1].len = NetworkParameterConstants.MTU;
            int dataLen = 0;

            fixed(network_iovec *iovptr = &iovecs[0])
            {
                dataLen = IPCManager.Instance.ReceiveMessageEx(Address, iovptr, 2, ref remote);
            }

            if (dataLen <= 0)
            {
                iovecs[0].len = iovecs[1].len = 0;
            }

            Assert.True(iovecs[0].len + iovecs[1].len == dataLen);
            Assert.True(iovecs[0].len == sizeof(UdpCHeader));
            m_LocalDataStream.WriteBytesWithUnsafePointer(iovecs[0].len);

            UdpCHeader header    = new UdpCHeader();
            var        reader    = new DataStreamReader(m_LocalDataStream, 0, sizeof(UdpCHeader));
            var        readerCtx = default(DataStreamReader.Context);

            Assert.True(reader.IsCreated);
            reader.ReadBytes(ref readerCtx, header.Data, sizeof(UdpCHeader));
            Assert.True(header.Type == (int)UdpCProtocol.Data);

            Assert.True(remote.Family == NetworkFamily.IPC);
            //Assert.True(remote.ipc_handle == from.ipc_handle);
            Assert.True(remote.Port == from.Port);

            Assert.True(iovecs[1].len == dataToCompare.Length);
            m_LocalDataStream.WriteBytesWithUnsafePointer(iovecs[1].len);

            reader    = new DataStreamReader(m_LocalDataStream, iovecs[0].len, dataToCompare.Length);
            readerCtx = default(DataStreamReader.Context);
            var received = reader.ReadBytesAsArray(ref readerCtx, dataToCompare.Length);

            for (int i = 0, n = dataToCompare.Length; i < n; ++i)
            {
                Assert.True(received[i] == dataToCompare[i]);
            }
        }
Exemplo n.º 10
0
        internal Reader(DataStreamReader reader)
        {
            var context = default(Context);
            var length  = reader.ReadInt(ref context);
            var bytes   = reader.ReadBytesAsArray(ref context, length);

            stream = new MemoryStream();
            using (var inStream = new MemoryStream(bytes)) {
                using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress)) {
                    deflateStream.CopyTo(stream);
                }
            }
            stream.Seek(0, SeekOrigin.Begin);
            this.reader = new BinaryReader(stream);
        }
        /// <summary>
        /// Parses data from streamReader according to the CommandType in the Message Header
        /// </summary>
        public static void parse(DataStreamReader streamReader)
        {
            //Tracks where in the data stream you are and how much you've read
            var readerContext = default(DataStreamReader.Context);

            //Attempt to read Message byte array from streamReader
            byte[] msgBytes = streamReader.ReadBytesAsArray(ref readerContext, streamReader.Length);

            Debug.Log(msgBytes.Length);

            //Convert msgBytes to object and attempt to cast as a Message
            Message msgRecieved = (Message)Helpers.byteArrayToObject(msgBytes);

            if (msgRecieved != null)   //Message object was recieved
            {
                msgRecieved.process(); //Process the message data
            }
        }
    public override void Read(int connectionId, DataStreamReader stream, ref DataStreamReader.Context context)
    {
        byte[]  buff = stream.ReadBytesAsArray(ref context, sizeof(float) * 7);
        Vector3 vect = Vector3.zero;

        vect.x = BitConverter.ToSingle(buff, 0 * sizeof(float));
        vect.y = BitConverter.ToSingle(buff, 1 * sizeof(float));
        vect.z = BitConverter.ToSingle(buff, 2 * sizeof(float));

        var rotation = Quaternion.identity;

        rotation.x = BitConverter.ToSingle(buff, 3 * sizeof(float));
        rotation.y = BitConverter.ToSingle(buff, 4 * sizeof(float));
        rotation.z = BitConverter.ToSingle(buff, 5 * sizeof(float));
        rotation.w = BitConverter.ToSingle(buff, 6 * sizeof(float));

        Target.rotation = rotation;
        Target.position = vect;
    }
    public override void Read(int connectionId, DataStreamReader stream, ref DataStreamReader.Context context)
    {
        var prefabId = stream.ReadInt(ref context);

        byte[]  buff     = stream.ReadBytesAsArray(ref context, sizeof(float) * 7);
        Vector3 position = Vector3.zero;

        position.x = BitConverter.ToSingle(buff, 0 * sizeof(float));
        position.y = BitConverter.ToSingle(buff, 1 * sizeof(float));
        position.z = BitConverter.ToSingle(buff, 2 * sizeof(float));

        var rotation = Quaternion.identity;

        rotation.x = BitConverter.ToSingle(buff, 3 * sizeof(float));
        rotation.y = BitConverter.ToSingle(buff, 4 * sizeof(float));
        rotation.z = BitConverter.ToSingle(buff, 5 * sizeof(float));
        rotation.w = BitConverter.ToSingle(buff, 6 * sizeof(float));

        Spawner.SpawnInServer(prefabId, position, rotation);
    }