Пример #1
0
        public void DisconnectFromARemoteEndPoint()
        {
            using (var host = new LocalDriverHelper(default(NetworkEndPoint)))
            {
                host.Host();
                var driver = new NetworkDriver(new IPCNetworkInterface(), new NetworkDataStreamParameter {
                    size = 64
                });

                // Need to be connected in order to be able to send a disconnect packet.
                NetworkConnection connectionId = driver.Connect(host.EndPoint);
                Assert.True(connectionId != default(NetworkConnection));
                driver.ScheduleUpdate().Complete();

                var local = driver.LocalEndPoint();
                host.Assert_GotConnectionRequest(local, true);

                NetworkConnection con;
                DataStreamReader  slice;
                // Pump so we get the accept message back.
                driver.ScheduleUpdate().Complete();
                Assert.AreEqual(NetworkEvent.Type.Connect, driver.PopEvent(out con, out slice));
                driver.Disconnect(connectionId);
                driver.ScheduleUpdate().Complete();

                host.Assert_GotDisconnectionRequest(local);

                driver.Dispose();
            }
        }
Пример #2
0
        public void DisconnectByRemote()
        {
            using (var host = new LocalDriverHelper(default(NetworkEndPoint)))
                using (var client = new NetworkDriver(new IPCNetworkInterface()))
                {
                    host.Host();
                    var popEvent = NetworkEvent.Type.Empty;
                    var c        = client.Connect(host.EndPoint);

                    client.ScheduleUpdate().Complete();
                    host.Assert_GotConnectionRequest(client.LocalEndPoint(), true);

                    byte             reason = 0;
                    DataStreamReader reader;
                    for (int frm = 0; frm < 10; ++frm)
                    {
                        if (c.GetState(client) == NetworkConnection.State.Connected)
                        {
                            c.Disconnect(client);
                        }

                        if ((popEvent = host.m_LocalDriver.PopEvent(out var id, out reader)) != NetworkEvent.Type.Empty)
                        {
                            reason = (reader.IsCreated && reader.Length > 0) ? reason = reader.ReadByte() : (byte)0;
                            break;
                        }
                        host.Update();
                        client.ScheduleUpdate().Complete();
                    }
                    Assert.AreEqual(NetworkEvent.Type.Disconnect, popEvent);
                    Assert.AreEqual((byte)DisconnectReason.ClosedByRemote, reason);
                }
        }
Пример #3
0
        public void SetupServerAndClientAndConnectThem(int bufferSize)
        {
            //setup server
            server_driver = NetworkDriver.Create(new NetworkDataStreamParameter {
                size = bufferSize
            });
            NetworkEndPoint server_endpoint = NetworkEndPoint.LoopbackIpv4;

            server_endpoint.Port = 1337;
            server_driver.Bind(server_endpoint);
            server_driver.Listen();

            //setup client
            client_driver = NetworkDriver.Create(new NetworkDataStreamParameter {
                size = bufferSize
            });
            clientToServerConnection = client_driver.Connect(server_endpoint);

            //update drivers
            client_driver.ScheduleUpdate().Complete();
            server_driver.ScheduleUpdate().Complete();

            //accept connection
            connectionToClient = server_driver.Accept();

            server_driver.ScheduleUpdate().Complete();
            ev = server_driver.PopEventForConnection(connectionToClient, out stream);
            Assert.IsTrue(ev == NetworkEvent.Type.Empty, "Not empty NetworkEvent on the server appeared");

            client_driver.ScheduleUpdate().Complete();
            ev = clientToServerConnection.PopEvent(client_driver, out stream);
            Assert.IsTrue(ev == NetworkEvent.Type.Connect, "NetworkEvent should have Type.Connect on the client");
        }
Пример #4
0
        public void DisconnectByMaxConnectionAttempts()
        {
            using (var host = new LocalDriverHelper(default(NetworkEndPoint)))
                using (var client = new NetworkDriver(new IPCNetworkInterface(), new NetworkConfigParameter {
                    maxConnectAttempts = 1, fixedFrameTimeMS = 10, connectTimeoutMS = 25
                }))
                {
                    host.Host();
                    var popEvent = NetworkEvent.Type.Empty;
                    var c        = client.Connect(host.EndPoint);
                    client.ScheduleUpdate().Complete();

                    byte reason = 0;
                    var  reader = default(DataStreamReader);
                    for (int frm = 0; frm < 10; ++frm)
                    {
                        if ((popEvent = client.PopEvent(out var id, out reader)) != NetworkEvent.Type.Empty)
                        {
                            reason = (reader.IsCreated && reader.Length > 0) ? reason = reader.ReadByte() : (byte)0;
                            break;
                        }
                        client.ScheduleUpdate().Complete();
                    }
                    Assert.AreEqual(NetworkEvent.Type.Disconnect, popEvent);
                    Assert.AreEqual((byte)DisconnectReason.MaxConnectionAttempts, reason);
                }
        }
Пример #5
0
        private void ClientReceivePackets(NetworkDriver clientDriver, int packetCount, NetworkConnection clientToServer, long startTime, int minDelay)
        {
            DataStreamReader readStrm;

            NetworkEvent.Type netEvent;
            var abortFrame = 0;

            while (true)
            {
                if (abortFrame++ > 125)
                {
                    Assert.Fail("Did not receive first delayed packet");
                }
                netEvent = clientToServer.PopEvent(clientDriver, out readStrm);
                if (netEvent == NetworkEvent.Type.Data)
                {
                    break;
                }
                m_ServerDriver.ScheduleUpdate().Complete();
                clientDriver.ScheduleUpdate().Complete();
            }

            // All delayed packets (from first patch) should be poppable now
            for (int i = 0; i < packetCount; i++)
            {
                var delay = m_ServerDriver.LastUpdateTime - startTime;
                Assert.AreEqual(NetworkEvent.Type.Data, netEvent);
                Assert.GreaterOrEqual(delay, minDelay, $"Delay too low on packet {i}");
                Assert.AreEqual(64, readStrm.Length);
                for (int j = 0; j < 16; j++)
                {
                    var read = readStrm.ReadInt();
                    Assert.AreEqual(i + 1, read);
                    Assert.True(read > 0 && read <= packetCount, "read incorrect value: " + read);
                }

                // Test done when all packets have been verified
                if (i == packetCount - 1)
                {
                    break;
                }

                // It could be not all patch of packets were processed in one update (depending on how the timers land)
                abortFrame = 0;
                while ((netEvent = clientToServer.PopEvent(clientDriver, out readStrm)) == NetworkEvent.Type.Empty)
                {
                    if (abortFrame++ > 75)
                    {
                        Assert.Fail("Didn't receive all delayed packets");
                    }
                    clientDriver.ScheduleUpdate().Complete();
                    m_ServerDriver.ScheduleUpdate().Complete();
                }
            }
        }
Пример #6
0
        private void TestPipeline(int packetCount, NetworkPipeline serverPipe, int packetDelay = 100)
        {
            // Connect to server
            var clientToServer  = m_ClientDriver.Connect(m_ServerDriver.LocalEndPoint());
            var clientToServer2 = m_ClientDriver2.Connect(m_ServerDriver.LocalEndPoint());

            Assert.AreNotEqual(default(NetworkConnection), clientToServer);
            Assert.AreNotEqual(default(NetworkConnection), clientToServer2);
            m_ClientDriver.ScheduleUpdate().Complete();
            m_ClientDriver2.ScheduleUpdate().Complete();

            // Driver only updates time in update, so must read start time before update
            var startTime = m_ServerDriver.LastUpdateTime;

            // Handle incoming connection from client
            m_ServerDriver.ScheduleUpdate().Complete();
            var serverToClient = m_ServerDriver.Accept();

            Assert.AreNotEqual(default(NetworkConnection), serverToClient);
            var serverToClient2 = m_ServerDriver.Accept();

            Assert.AreNotEqual(default(NetworkConnection), serverToClient2);

            // Send given packetCount number of packets in a row in one update
            // Write 1's for packet 1, 2's for packet 2 and so on and verify they're received in same order
            for (int i = 0; i < packetCount; i++)
            {
                if (m_ServerDriver.BeginSend(serverPipe, serverToClient, out var strm) == 0 &&
                    m_ServerDriver.BeginSend(serverPipe, serverToClient2, out var strm2) == 0)
                {
                    for (int j = 0; j < 16; j++)
                    {
                        strm.WriteInt((int)i + 1);
                        strm2.WriteInt((int)i + 1);
                    }
                    m_ServerDriver.EndSend(strm);
                    m_ServerDriver.EndSend(strm2);
                }
            }

            m_ServerDriver.ScheduleUpdate().Complete();

            // Receive incoming message from server
            m_ClientDriver.ScheduleUpdate().Complete();
            m_ClientDriver2.ScheduleUpdate().Complete();
            DataStreamReader readStrm;

            Assert.AreEqual(NetworkEvent.Type.Connect, clientToServer.PopEvent(m_ClientDriver, out readStrm));
            Assert.AreEqual(NetworkEvent.Type.Connect, clientToServer.PopEvent(m_ClientDriver2, out readStrm));

            ClientReceivePackets(m_ClientDriver, packetCount, clientToServer, startTime, packetDelay);
            ClientReceivePackets(m_ClientDriver2, packetCount, clientToServer2, startTime, packetDelay);
        }
    void Update()
    {   //Ready to process events
        m_Driver.ScheduleUpdate().Complete();

        // CleanUpConnections
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                playersIds.RemoveAtSwapBack(i);
                --i;
            }
        }
        //Send data to clients
        SendDataToClients();

        // AcceptNewConnections
        NetworkConnection c = m_Driver.Accept();

        while (c != default(NetworkConnection))
        {
            OnConnect(c);

            // Check if there is another new connection
            c = m_Driver.Accept();
        }

        // Read Incoming Messages
        ReadIncomingMessages();
    }
Пример #8
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();
        if (playerID != "0")
        {
            GameObject.FindGameObjectWithTag("Ball").GetComponent <Ball>().invert = -1;
        }
        if (!m_Connection.IsCreated)
        {
            return;
        }

        DataStreamReader stream;

        NetworkEvent.Type cmd;
        cmd = m_Connection.PopEvent(m_Driver, out stream);
        while (cmd != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                OnConnect();
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                OnData(stream);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Disconnect();
            }

            cmd = m_Connection.PopEvent(m_Driver, out stream);
        }
    }
Пример #9
0
    private void Update()
    {
        driver.ScheduleUpdate().Complete();

        if (!connection.IsCreated)
        {
            if (!Done)
            {
                Debug.Log("Something went wrong during connect");
            }
            return;
        }

        DataStreamReader reader;

        NetworkEvent.Type cmd;
        while ((cmd = connection.PopEvent(driver, out reader)) != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                Debug.Log("We are now connected to the server");
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                packetHandlers[reader.ReadUShort()](reader);
                Done = true;
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Client got disconnected from server");
                connection = default(NetworkConnection);
                ClientHandle.OnDisconnect?.Invoke();
            }
        }
    }
Пример #10
0
    public void Update()
    {
        m_Tick++;
        m_UpdateHandle.Complete();

        if (m_PendingDisconnects.IsCreated)
        {
            m_PendingDisconnects.Dispose();
        }

        var acceptJob = new SoakServerAcceptJob
        {
            now         = m_Tick,
            driver      = m_ServerDriver,
            connections = m_Connections
        };
        var soakJob = new SoakServerUpdateClientsJob
        {
            driver      = m_ServerDriver.ToConcurrent(),
            pipeline    = m_Pipeline,
            connections = m_Connections.AsDeferredJobArray()
        };

        /*var time = Time.fixedTime;
         * if (time > m_NextStatsPrint)
         * {
         *  PrintStatistics();
         *  m_NextStatsPrint = time + 10;
         * }*/

        m_UpdateHandle = m_ServerDriver.ScheduleUpdate();
        m_UpdateHandle = acceptJob.Schedule(m_UpdateHandle);
        m_UpdateHandle = soakJob.Schedule(m_Connections, 1, m_UpdateHandle);
    }
Пример #11
0
    private void Update()
    {
        mJob.Complete();

        // copy connection state from native container
        mState = mConnection[0].GetState(mDriver);

        // copy received events from native container
        var decode = new DecodeEvent();

        for (var i = 0; i < mEvents.Length; i++)
        {
            mLog.Add(decode.Call(mEvents[i]));
            mEvents.RemoveAtSwapBack(i);
            --i;
        }

        // copy pending events to native container to send to host
        while (mLog.HasPending)
        {
            mEvents.Add(mLog.PopPending().Into());
        }

        // schedule next update
        var update = new UpdateJob(mDriver, mConnection, mEvents);

        mJob = mDriver.ScheduleUpdate();
        mJob = update.Schedule(mJob);
    }
Пример #12
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        if (!m_Connection.IsCreated)
        {
            return;
        }

        DataStreamReader stream;

        NetworkEvent.Type cmd;
        cmd = m_Connection.PopEvent(m_Driver, out stream);
        while (cmd != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                OnConnect();
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                OnData(stream);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                OnDisconnect();
            }

            cmd = m_Connection.PopEvent(m_Driver, out stream);
        }
    }
Пример #13
0
        void Update()
        {
            ServerJobHandle.Complete();

            var connectionJob = new ServerUpdateConnectionsJob
            {
                driver      = m_Driver,
                connections = m_Connections,
            };

            var serverUpdateJob = new ServerUpdateJob
            {
                driver                  = m_Driver,
                pipeline                = m_Pipeline,
                connections             = m_Connections,
                rooms                   = m_Room,
                connectedClients        = m_ConnectedClients,
                connectionIndexToRoomID = m_ConnectionIndexToRoomID,
                serverAddressToRoomID   = m_ServerAddressToRoomID,
                ReleasedRooms           = m_ReleasedRoomIds,
            };

            ServerJobHandle = m_Driver.ScheduleUpdate();
            ServerJobHandle = connectionJob.Schedule(ServerJobHandle);
            ServerJobHandle = serverUpdateJob.Schedule(ServerJobHandle);
        }
Пример #14
0
    private void Update()
    {
        //FORCE THE UPDATE TO RUN AT THE SAME RATE AS NORMAL UPDATE
        m_Driver.ScheduleUpdate().Complete();

        if (!m_Connection.IsCreated)
        {
            return;
        }


        //HANDLE MESSAGES
        DataStreamReader stream;

        NetworkEvent.Type cmd;

        //START CHECKING FOR EVENT WHICH MIGHT HAVE HAPPENED
        while ((cmd = m_Connection.PopEvent(m_Driver, out stream)) != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                OnClientConnected();
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                OnDataMessage(stream, m_Connection);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("CLIENT:: got a disconnect messsage");
                m_Connection = default;
            }
        }
    }
Пример #15
0
        public void Accept()
        {
            Driver.Bind(NetworkEndPoint.LoopbackIpv4);
            Driver.Listen();
            Assert.That(Driver.Listening);

            // create connection to test to connect.
            /*var remote =*/ RemoteDriver.Connect(Driver.LocalEndPoint());

            NetworkConnection id;
            DataStreamReader  reader;
            const int         maximumIterations = 10;
            int  count     = 0;
            bool connected = false;

            while (count++ < maximumIterations)
            {
                // Clear pending events
                Driver.PopEvent(out id, out reader);
                RemoteDriver.PopEvent(out id, out reader);

                Driver.ScheduleUpdate().Complete();
                RemoteDriver.ScheduleUpdate().Complete();
                var connection = Driver.Accept();
                if (connection != default(NetworkConnection))
                {
                    connected = true;
                }
            }

            Assert.That(connected);
        }
Пример #16
0
    private void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        //Não está conectado
        if (!m_Connection.IsCreated)
        {
            if (!Done)
            {
                return;
            }
        }

        while ((cmd = m_Driver.PopEvent(out m_Connection, out DataStreamReader reader)) != NetworkEvent.Type.Empty)
        {
            //Receiving data from client
            if (cmd == NetworkEvent.Type.Data)
            {
                int num = reader.ReadInt();
                Debug.Log("Numero recebido: " + num);

                total += num;

                var writer = m_Driver.BeginSend(NetworkPipeline.Null, m_Connections[i]);
                writer.WriteInt(total);
                m_Driver.EndSend(writer);
            }
            //Check if the message of client is a disconnection
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Cliente " + i + " desconectou");
                m_Connections[i] = default(NetworkConnection);
            }
        }
    }
Пример #17
0
    // fired constantly until client program ends
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();
        //if connection has not been created
        if (!m_Connection.IsCreated)
        {
            return;
        }
        DataStreamReader stream;

        NetworkEvent.Type cmd;
        cmd = m_Connection.PopEvent(m_Driver, out stream);
        while (cmd != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                OnConnect();
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                OnData(stream);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                OnDisconnect();
            }
            cmd = m_Connection.PopEvent(m_Driver, out stream);
        }

        if (FindPlayerCube(clientPlayer) != null)
        {
            UpdateClientPlayer();
        }
    }
Пример #18
0
        public void ShouldAcceptConnection()
        {
            Server.Instance.Init(new ushort[] { 9099 }, 100, true, false);
            var serverDriver = new NetworkDriver(new IPCNetworkInterface(), new NetworkDataStreamParameter {
                size = 64
            });

            Server.Instance.Start(serverDriver);

            // send out connection request
            var clientDriver = new NetworkDriver(new IPCNetworkInterface(), new NetworkDataStreamParameter {
                size = 64
            });
            NetworkConnection networkConnection = clientDriver.Connect(serverDriver.LocalEndPoint());

            Assert.True(networkConnection != default);
            clientDriver.ScheduleUpdate().Complete();

            var numberOfConnectedClients = 0;
            var onClientConnected        = new Server.ConnectionDelegate(id => numberOfConnectedClients++);

            Server.Instance.ClientConnected += onClientConnected;
            Server.Instance.Tick();
            Assert.AreEqual(1, numberOfConnectedClients);
            Server.Instance.ClientConnected -= onClientConnected;

            if (clientDriver.IsCreated)
            {
                clientDriver.Dispose();
            }
        }
    private void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        if (!m_Connection.IsCreated)
        {
            return;
        }


        DataStreamReader stream;

        NetworkEvent.Type cmd;

        while ((cmd = m_Connection.PopEvent(m_Driver, out stream)) != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                Debug.Log("Connected to the server.");
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                OnData(stream);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Client disconnected");
                m_Connection = default(NetworkConnection);
            }
        }
    }
Пример #20
0
        public void ConnectAttemptWithRetriesToARemoteEndPoint()
        {
            NetworkConnection connection;

            NetworkEvent.Type eventType = 0;
            DataStreamReader  reader;

            // Tiny connect timeout for this test to be quicker
            using (var client = new NetworkDriver(new IPCNetworkInterface(), new NetworkDataStreamParameter {
                size = 64
            },
                                                  new NetworkConfigParameter {
                connectTimeoutMS = 15, maxConnectAttempts = 10, fixedFrameTimeMS = 10
            }))
            {
                var hostAddress = NetworkEndPoint.LoopbackIpv4.WithPort(1);
                client.Connect(hostAddress);

                // Wait past the connect timeout so there will be unanswered connect requests
                client.ScheduleUpdate().Complete();
                client.ScheduleUpdate().Complete();

                using (var host = new LocalDriverHelper(hostAddress))
                {
                    host.Host();

                    // Now give the next connect attempt time to happen
                    // TODO: Would be better to be able to see internal state here and explicitly wait until next connect attempt happens
                    //client.ScheduleUpdate().Complete();

                    host.Assert_GotConnectionRequest(client.LocalEndPoint(), true);

                    // Wait for the client to get the connect event back
                    for (int i = 0; i < 2; ++i)
                    {
                        client.ScheduleUpdate().Complete();
                        eventType = client.PopEvent(out connection, out reader);
                        if (eventType != NetworkEvent.Type.Empty)
                        {
                            break;
                        }
                    }

                    Assert.AreEqual(NetworkEvent.Type.Connect, eventType);
                }
            }
        }
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        // CleanUpConnections
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                playersManager.RemovePlayer(m_Connections[i].InternalId);
                --i;
            }
        }

        // AcceptNewConnections
        NetworkConnection c = m_Driver.Accept();

        while (c != default(NetworkConnection))
        {
            OnConnect(c);

            // Check if there is another new connection
            c = m_Driver.Accept();
        }

        DataStreamReader stream;

        for (int i = 0; i < m_Connections.Length; i++)
        {
            Assert.IsTrue(m_Connections[i].IsCreated);

            NetworkEvent.Type cmd;
            cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            while (cmd != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    OnData(stream, m_Connections[i].InternalId);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    OnDisconnect(i);
                }

                cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            }
        }

        if (playersManager.IsDirtyFlag)
        {
            for (int i = 0; i < m_Connections.Length; i++)
            {
                ServerUpdateMsg m = new ServerUpdateMsg(playersManager.GetPlayers());
                SendToClient(JsonUtility.ToJson(m), m_Connections[i]);
            }
            playersManager.ClearDirtyFlag();
        }
    }
    private void Update()
    {
        m_Driver.ScheduleUpdate().Complete(); //Tells the driver we're ready to listen for the next event

        CleanUpConnections();
        AcceptNewConnections();
        ReadIncomingMessages();
    }
Пример #23
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        ClearConnections();
        AcceptConnections();
        ReceiveMessages();
    }
Пример #24
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();


        // AcceptNewConnections
        NetworkConnection c = m_Driver.Accept();

        while (c != default(NetworkConnection))
        {
            OnConnect(c);

            // Check if there is another new connection
            c = m_Driver.Accept();
        }

        // CleanUpConnections
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                --i;
            }
        }

        GameLoop();

        // Read Incoming Messages
        DataStreamReader stream;

        for (int i = 0; i < m_Connections.Length; i++)
        {
            Assert.IsTrue(m_Connections[i].IsCreated);

            NetworkEvent.Type cmd;
            cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            while (cmd != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    OnData(stream, i);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    OnDisconnect(i);
                }

                cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            }
            //Debug.Log("Players Time: " + ConnectedList.GameState[i].pulse + " Server Time: " + DateTime.Now +" Player Time In Seconds: " + ConnectedList.GameState[i].pulse.Second);
            //Debug.Log("Time Difference: " + (DateTime.Now - ConnectedList.GameState[i].pulse) + " Time Span Amount: " + TimeSpan.FromSeconds(5));
            if ((DateTime.Now - ConnectedList.GameState[i].pulse) > TimeSpan.FromSeconds(5))
            {
                OnDisconnect(i);
            }
        }
    }
Пример #25
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        // CleanUpConnections
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                --i;
            }
        }

        // AcceptNewConnections
        NetworkConnection c = m_Driver.Accept();

        while (c != default(NetworkConnection))
        {
            OnConnect(c);

            // Check if there is another new connection
            c = m_Driver.Accept();
        }

        //remove Inactive players
        for (int i = 0; i < m_Players.Count; i++)
        {
            if (Time.time - m_Players[i].timeOfLastMsg > 5.0f)
            {
                OnDisconnect(i);
            }
        }

        // Read Incoming Messages
        DataStreamReader stream;

        for (int i = 0; i < m_Connections.Length; i++)
        {
            Assert.IsTrue(m_Connections[i].IsCreated);

            NetworkEvent.Type cmd;
            cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            while (cmd != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    OnData(stream, i);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    OnDisconnect(i);
                }

                cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream);
            }
        }
    }
    void FixedUpdate()
    {
        // Update the ping client UI with the ping statistics computed by teh job scheduled previous frame since that
        // is now guaranteed to have completed
        PingClientUIBehaviour.UpdateStats(m_numPingsSent, m_lastPingTime);

        // Update the NetworkDriver. It schedules a job so we must wait for that job with Complete
        m_ClientDriver.ScheduleUpdate().Complete();

        // If the client ui indicates we should be sending pings but we do not have an active connection we create one
        if (PingClientUIBehaviour.ServerEndPoint.IsValid && !m_clientToServerConnection.IsCreated)
        {
            m_clientToServerConnection = m_ClientDriver.Connect(PingClientUIBehaviour.ServerEndPoint);
        }
        // If the client ui indicates we should not be sending pings but we do have a connection we close that connection
        if (!PingClientUIBehaviour.ServerEndPoint.IsValid && m_clientToServerConnection.IsCreated)
        {
            m_clientToServerConnection.Disconnect(m_ClientDriver);
            m_clientToServerConnection = default(NetworkConnection);
        }

        DataStreamReader strm;

        NetworkEvent.Type cmd;
        // Process all events on the connection. If the connection is invalid it will return Empty immediately
        while ((cmd = m_clientToServerConnection.PopEvent(m_ClientDriver, out strm)) != NetworkEvent.Type.Empty)
        {
            if (cmd == NetworkEvent.Type.Connect)
            {
                // When we get the connect message we can start sending data to the server
                // Set the ping id to a sequence number for the new ping we are about to send
                m_pendingPing = new PendingPing {
                    id = m_numPingsSent, time = Time.fixedTime
                };
                // Create a 4 byte data stream which we can store our ping sequence number in
                if (m_ClientDriver.BeginSend(m_clientToServerConnection, out var pingData) == 0)
                {
                    pingData.WriteInt(m_numPingsSent);
                    m_ClientDriver.EndSend(pingData);
                }
                // Update the number of sent pings
                ++m_numPingsSent;
            }
            else if (cmd == NetworkEvent.Type.Data)
            {
                // When the pong message is received we calculate the ping time and disconnect
                m_lastPingTime = (int)((Time.fixedTime - m_pendingPing.time) * 1000);
                m_clientToServerConnection.Disconnect(m_ClientDriver);
                m_clientToServerConnection = default(NetworkConnection);
            }
            else if (cmd == NetworkEvent.Type.Disconnect)
            {
                // If the server disconnected us we clear out connection
                m_clientToServerConnection = default(NetworkConnection);
            }
        }
    }
Пример #27
0
    public virtual void Update()
    {
        //FORCE THE NETDRIVER TO USE THE NORMAL UPDATE LOOP
        m_Driver.ScheduleUpdate().Complete();

        //CLEAN UP CONNECTIONS
        //if not made
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                --i;
            }
        }

        //ACCEPT NEW CONNECTIONS
        NetworkConnection c;

        //asks for any new connection
        while ((c = m_Driver.Accept()) != default)
        {
            //if it's not null
            //ADD THE NEW CONECTION
            m_Connections.Add(c);
        }

        //START CHECKING FOR EVENT WHICH MIGHT HAVE HAPPENED
        DataStreamReader stream;

        for (int i = 0; i < m_Connections.Length; i++)
        {
            //if the connection is not created
            if (!m_Connections[i].IsCreated)
            {
                continue; //skip it
            }
            //if we have a connection
            //check for an event
            NetworkEvent.Type cmd;
            while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty)
            {
                //start filtering events
                //DATA
                if (cmd == NetworkEvent.Type.Data)
                {
                    OnDataMessage(stream, m_Connections[i]);
                }
                //DISCONNECT
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log(LogPrefix + "Client asked to disconnect");
                    m_Connections[i] = default;
                }
            }
        }
    }
Пример #28
0
    void Update()
    {
        driver.ScheduleUpdate().Complete();

        if (!connection.IsCreated)
        {
            //Debug.Log( "Client | Something went wrong during connect" );
            return;
        }

        DataStreamReader stream;

        Unity.Networking.Transport.NetworkEvent.Type cmd;
        while ((cmd = connection.PopEvent(driver, out stream)) != Unity.Networking.Transport.NetworkEvent.Type.Empty)
        {
            if (cmd == Unity.Networking.Transport.NetworkEvent.Type.Connect)
            {
                isConnected.Value = true;
                Debug.Log("Client | We are now connected to the server");
                eventsToSend.Add(updatePlayerNameEvent);
            }
            else if (cmd == Unity.Networking.Transport.NetworkEvent.Type.Data)
            {
                int packetID = stream.ReadInt();
                Debug.Log("Client | Recieved packet: " + allEvents.Items[packetID].displayName);

                //Handle recieved events.
                allEvents.Items[packetID].ReadPacket(stream);
                lastRecievedPacket.Value = allEvents.Items[packetID].displayName;
            }
            else if (cmd == Unity.Networking.Transport.NetworkEvent.Type.Disconnect)
            {
                Debug.Log("Client | Got disconnected from server");
                isConnected.Value = false;
                SceneManager.LoadSceneAsync(sceneToLoadOnDisconnect);
                if (GameObject.Find("ClientBehaviour"))
                {
                    Destroy(GameObject.Find("ClientBehaviour"));
                }
                if (GameObject.Find("HostBehaviour"))
                {
                    Destroy(GameObject.Find("HostBehaviour"));
                }
                connection = default(NetworkConnection);
            }
        }

        //Send queued events.
        for (int i = 0; i < eventsToSend.Items.Count; i++)
        {
            Debug.Log("Client | Sending packet: " + eventsToSend.Items[i].displayName);
            var writer = driver.BeginSend(NetworkPipeline.Null, connection);
            writer = eventsToSend.Items[i].WritePacket(writer);
            driver.EndSend(writer);
        }
        eventsToSend.Items.Clear();
    }
Пример #29
0
 private void Update()
 {
     if (driver.IsCreated)
     {
         driver.ScheduleUpdate().Complete();
         UpdateConnections();
         ReadConnections();
     }
 }
Пример #30
0
        public void CreateAndConnect_NetworkConnection_ToRemoteEndPoint()
        {
            var connection = Driver.Connect(RemoteDriver.LocalEndPoint());

            Assert.That(connection.IsCreated);
            Driver.ScheduleUpdate().Complete();

            RemoteDriver.ScheduleUpdate().Complete();
            Assert.That(RemoteDriver.Accept().IsCreated);

            Driver.ScheduleUpdate().Complete();
            DataStreamReader reader;

            Assert.That(connection.PopEvent(Driver, out reader) == NetworkEvent.Type.Connect);
        }