コード例 #1
0
        public void SetupServerAndClientAndConnectThem(int bufferSize)
        {
            //setup server
            server_driver = new UdpNetworkDriver(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 = new UdpNetworkDriver(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");
        }
コード例 #2
0
    public void Connect()
    {
        m_Connection = default(NetworkConnection);
        var endpoint = NetworkConfig.GetClientEndPoint();

        m_Connection = m_Driver.Connect(endpoint);
    }
コード例 #3
0
ファイル: SocketTests.cs プロジェクト: zs782306174/DOTSSample
        public void UdpC_ConnectSendTest_ShouldConnectAndReceiveData()
        {
            using (var server = new UdpNetworkDriver(new NetworkDataStreamParameter {
            }))
                using (var client = new UdpNetworkDriver(new NetworkDataStreamParameter {
                }))
                {
                    var serverPort = 50008;

                    server.Bind(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));
                    client.Bind(NetworkEndPoint.LoopbackIpv4);

                    server.Listen();

                    client.Connect(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));

                    NetworkConnection serverConnection, clientConnection;
                    int maxIterations = 100;

                    ConnectTogether(server, client, maxIterations, out serverConnection, out clientConnection);

                    var message = new byte[]
                    {
                        (byte)'m',
                        (byte)'e',
                        (byte)'s',
                        (byte)'s',
                        (byte)'a',
                        (byte)'g',
                        (byte)'e'
                    };

                    SendReceive(client, server, clientConnection, serverConnection, message, maxIterations);
                }
        }
コード例 #4
0
    public void ConnectToServer()
    {
        debugTextField.text = "";

        string ip = serverIP.text;

        if (!m_Connection.IsCreated || lastIP != ip)
        {
            if (m_Connection.IsCreated)
            {
                m_Connection.Disconnect(m_Driver);
                m_Connection = default(NetworkConnection);
            }

            lastIP = ip;
            if (ip == "")
            {
                ip = "127.0.0.1";
            }
            var endpoint = NetworkEndPoint.Parse(ip, 9000);
            m_Connection = m_Driver.Connect(endpoint);
        }
        else
        {
            //send message for new hello
            using (var writer = PacketFunctions.WritePacket(GameEvent.HELLO_SERVER)) {
                //m_Connection.Send(m_Driver, writer);
                m_Connection.Send(m_Driver, reliableUdpPipe, writer);
            }
        }
    }
コード例 #5
0
ファイル: Client.cs プロジェクト: JulianHeitkamp/AntiYoyClone
 public void Join(string ip, string name)
 {
     endpoint   = NetworkEndPoint.Parse(ip, 9000);
     connection = driver.Connect(endpoint);
     started    = true;
     me         = new NetworkPlayer(0, 0, name);
 }
コード例 #6
0
ファイル: SocketTests.cs プロジェクト: zs782306174/DOTSSample
        public void UdpC_ReconnectAndResend_ShouldReconnectAndResend()
        {
            using (var server = new UdpNetworkDriver(new NetworkDataStreamParameter {
            }))
                using (var client = new UdpNetworkDriver(new NetworkDataStreamParameter {
                }))
                {
                    var serverPort = 50007;

                    server.Bind(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));
                    client.Bind(NetworkEndPoint.LoopbackIpv4);

                    server.Listen();

                    NetworkConnection serverConnection, clientConnection;
                    int maxIterations = 100;

                    var id = client.Connect(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));
                    ConnectTogether(server, client, maxIterations, out serverConnection, out clientConnection);

                    client.Disconnect(id);

                    server.ScheduleUpdate().Complete();

                    var data = new byte[1472];
                    var size = 1472;
                    NetworkConnection from;

                    Assert.AreEqual(ExperimentalEventType.Disconnect, PollEvent(ExperimentalEventType.Disconnect, maxIterations, server, ref data, out size, out from));

                    id = client.Connect(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));
                    ConnectTogether(server, client, maxIterations, out serverConnection, out clientConnection);

                    var message = new byte[]
                    {
                        (byte)'m',
                        (byte)'e',
                        (byte)'s',
                        (byte)'s',
                        (byte)'a',
                        (byte)'g',
                        (byte)'e'
                    };

                    SendReceive(client, server, clientConnection, serverConnection, message, maxIterations);
                }
        }
コード例 #7
0
            public void Execute()
            {
                // If we should be sending pings but we do not have an active connection we create one
                if (!connection[0].IsCreated)
                {
                    connection[0] = driver.Connect(serverEp);
                }

                NetworkEvent.Type cmd;

                // Process all events on the connection. If the connection is invalid it will return Empty immediately
                while ((cmd = connection[0].PopEvent(driver, out var pingStream)) != NetworkEvent.Type.Empty)
                {
                    switch (cmd)
                    {
                    case 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
                        pendingPings[0] = new PendingPing
                        {
                            id   = numPings[0],
                            time = DateTime.UtcNow.Ticks
                        };

                        // Create a 4 byte data stream which we can store our ping sequence number in
                        var pingData = new DataStreamWriter(4, Allocator.Temp);
                        pingData.Write(numPings[0]);
                        connection[0].Send(driver, pingData);

                        // Update the number of sent pings
                        numPings[0] = numPings[0] + 1;
                        break;

                    case NetworkEvent.Type.Data:
                        lastPing[0] = (ushort)((DateTime.UtcNow.Ticks - pendingPings[0].time) / TimeSpan.TicksPerMillisecond);

                        // Validate data from pong matches ping
                        // TODO: Change if we ever support more than 1 pending ping
                        var readerCtx = default(DataStreamReader.Context);
                        var id        = pingStream.ReadInt(ref readerCtx);
                        var pingId    = numPings[0] - 1;

                        if (id != pingId)
                        {
                            Debug.LogWarning($"Received pong from server, but got wrong sequence number (Expected {pingId} but got {id})");
                        }

                        connection[0].Disconnect(driver);
                        connection[0] = default;
                        break;

                    case NetworkEvent.Type.Disconnect:
                        // If the server disconnected us we clear out connection
                        connection[0] = default;
                        break;
                    }
                }
            }
コード例 #8
0
        public void Connect(NetworkEndPoint endpoint)
        {
            if (connectEntity != Entity.Null)
            {
                Debug.LogError("connectEntity != Entity.Null");
                return;
            }

            if (_unreliablePipeline == NetworkPipeline.Null)
            {
#if UNITY_EDITOR
                if (clientPacketDelay > 0 || clientPacketDrop > 0)
                {
                    _unreliablePipeline = _driver.CreatePipeline(typeof(SimulatorPipelineStage), typeof(SimulatorPipelineStageInSend));
                }
                else
#endif
                {
                    _unreliablePipeline = _driver.CreatePipeline(typeof(NullPipelineStage));
                }
            }
            if (_reliablePipeline == NetworkPipeline.Null)
            {
#if UNITY_EDITOR
                if (clientPacketDelay > 0 || clientPacketDrop > 0)
                {
                    _reliablePipeline = _driver.CreatePipeline(typeof(SimulatorPipelineStageInSend), typeof(ReliableSequencedPipelineStage), typeof(SimulatorPipelineStage));
                }
                else
#endif
                {
                    _reliablePipeline = _driver.CreatePipeline(typeof(ReliableSequencedPipelineStage));
                }
            }

            if (closeQuery == null)
            {
                closeQuery = GetEntityQuery(new EntityQueryDesc
                {
                    All = new ComponentType[] { ComponentType.ReadOnly <NetworkDisconnectedMessage>(), /*ComponentType.ReadOnly<NetworkConnection>()*/ },
                });
            }


            //
            var connection = _driver.Connect(endpoint);
            connectEntity = EntityManager.CreateEntity();
            EntityManager.AddComponentData(connectEntity, new NetworkConnection {
                value = connection
            });
            EntityManager.AddComponent <NetworkInBuffer>(connectEntity);
            EntityManager.AddComponent <NetworkReliableOutBuffer>(connectEntity);
            EntityManager.AddComponent <NetworkUnreliableOutBuffer>(connectEntity);
            //EntityManager.AddComponent<NetworkConnectedMessage>(connectEntity);
            EntityManager.AddComponent <NetworkConnectMessage>(connectEntity);
#if UNITY_EDITOR
            EntityManager.SetName(connectEntity, "cNetworkConnection");
#endif
        }
コード例 #9
0
        public void Execute()
        {
            var ent = commandBuffer.CreateEntity();

            commandBuffer.AddComponent(ent, new PingClientConnectionComponentData {
                connection = driver.Connect(serverEP)
            });
        }
コード例 #10
0
    void Start()
    {
        m_Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        m_Connection = default(NetworkConnection);

        var endpoint = NetworkEndPoint.Parse(serverIP, 12345);

        m_Connection = m_Driver.Connect(endpoint);
    }
コード例 #11
0
        public void Execute()
        {
            Entity clientEntity = commandBuffer.CreateEntity();

            Debug.Log("about to send a connection request");
            commandBuffer.AddComponent(clientEntity, new NetworkClientConnection {
                connection = driver.Connect(serverEndPoint)
            });
        }
コード例 #12
0
        /// <summary>
        /// Connects the client to the server.
        /// </summary>
        private void connectToServer()
        {
            if (networkEndPoint != null || configureNetworkEndpoint())
            {
                Debug.Log("<color=lime><b>[Client]</b></color> Attempting to connect to server.");
                connectionToServer = networkDriver.Connect(networkEndPoint);

                StartCoroutine(checkForConnectionTimeout());
            }
        }
コード例 #13
0
    void Start()
    {
        RotatingCubePrefab = Resources.Load("CubeOBJ", typeof(GameObject)) as GameObject;
        networkDriver      = new UdpNetworkDriver(new INetworkParameter[0]);
        Connection         = default(NetworkConnection);
        var endpoint = NetworkEndPoint.Parse(serverAddress, serverPort);

        Connection = networkDriver.Connect(endpoint);
        InvokeRepeating("HeartBeat", 1, 1);
    }
コード例 #14
0
    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
                var pingData = new DataStreamWriter(4, Allocator.Temp);
                pingData.Write(m_numPingsSent);
                m_clientToServerConnection.Send(m_ClientDriver, 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);
            }
        }
    }
コード例 #15
0
    void Start()
    {
        Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        Connection = default(NetworkConnection);

        NetworkEndPoint endpoint = NetworkEndPoint.LoopbackIpv4;

        endpoint.Port = ServerPort;

        Connection = Driver.Connect(endpoint);
    }
コード例 #16
0
    void Start()
    {
        m_Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        m_Connection = default(NetworkConnection);
        var endpoint = NetworkEndPoint.Parse(serverIP, portNumber);

        m_Connection         = m_Driver.Connect(endpoint);
        clientStatus.text    = "Client Status: Offline";
        messageReceived.text = "";
        activeCubes          = 0;
        clientPositions      = new List <Vector2>();
    }
コード例 #17
0
    //Connection to the driver
    public bool Connect(ushort port = 9000, string address = "localhost")
    {
        var endpoint = NetworkEndPoint.LoopbackIpv4;

        endpoint.Port = 9000;//NetworkEndPoint.Parse(address, port);
        m_Connection  = m_Driver.Connect(endpoint);
        if (!m_Connection.IsCreated)
        {
            ErrorMessage = "Bad Gateway - Failed to connect to server.";
        }

        return(m_Connection.IsCreated);
    }
コード例 #18
0
    //string Ip = "";

    // Use this for initialization
    void Start()
    {
        Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        Connection = default(NetworkConnection);

        NetworkEndPoint endpoint = NetworkEndPoint.LoopbackIpv4;

        endpoint.Port = ServerPort;

        Connection = Driver.Connect(endpoint);
        ChildFirstPersonCharacter = gameObject.transform.GetChild(0).gameObject;
        ClientObjects             = new Dictionary <int, GameObject>();
    }
コード例 #19
0
    // Use this for initialization
    void Start()
    {
        Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        Connection = new NativeArray <NetworkConnection>(1, Allocator.Persistent);
        Done       = new NativeArray <byte>(1, Allocator.Persistent);

        ushort          serverPort = 9000;
        NetworkEndPoint endpoint   = NetworkEndPoint.LoopbackIpv4;

        endpoint.Port = serverPort;

        Connection[0] = Driver.Connect(endpoint);
    }
コード例 #20
0
    // Start is called before the first frame update
    private void Start()
    {
        m_Driver = new UdpNetworkDriver(new SimulatorUtility.Parameters {
            MaxPacketSize = 256, MaxPacketCount = 30, PacketDelayMs = 100
        });
        m_Pipeline   = m_Driver.CreatePipeline(typeof(UnreliableSequencedPipelineStage), typeof(SimulatorPipelineStage));
        m_Connection = default;

        m_Endpoint = new NetworkEndPoint();
        m_Endpoint = NetworkEndPoint.Parse("127.0.0.1", 9000);

        m_Connection = m_Driver.Connect(m_Endpoint);
    }
コード例 #21
0
ファイル: SocketTests.cs プロジェクト: zs782306174/DOTSSample
        public void UdpC_ListenThenConnect_ShouldFail()
        {
            using (var socket = new UdpNetworkDriver(new NetworkDataStreamParameter {
            }))
            {
                var endpoint = NetworkEndPoint.CreateIpv4(0, 50007);
                socket.Bind(endpoint);

                socket.Listen();

                var error = Assert.Throws <SocketException>(() => { socket.Connect(endpoint); });
                Assert.AreEqual(error.SocketErrorCode, SocketError.AddressNotAvailable);
            }
        }
コード例 #22
0
    void Start()
    {
        m_Driver = new UdpNetworkDriver(new NetworkDataStreamParameter {
            size = bufferSize
        });
        m_Connection = default(NetworkConnection);

        NetworkEndPoint client_endpoint = NetworkEndPoint.LoopbackIpv4;

        client_endpoint.Port = 9000;
        m_Connection         = m_Driver.Connect(client_endpoint);
        cts = new Serializer <CustomType>();
        cts.Initialize();
    }
コード例 #23
0
    // Start is called before the first frame update
    private void Start()
    {
        m_Driver = new UdpNetworkDriver(new SimulatorUtility.Parameters {
            MaxPacketSize = 256, MaxPacketCount = 30, PacketDelayMs = 100
        });
        m_Pipeline   = m_Driver.CreatePipeline(typeof(UnreliableSequencedPipelineStage), typeof(SimulatorPipelineStage));
        m_Connection = new NativeArray <NetworkConnection>(1, Allocator.Persistent);
        m_Done       = new NativeArray <byte>(1, Allocator.Persistent);

        m_Endpoint = new NetworkEndPoint();
        m_Endpoint = NetworkEndPoint.Parse("127.0.0.1", 9000);

        m_Connection[0] = m_Driver.Connect(m_Endpoint);
    }
コード例 #24
0
        private void InitClient(ReceiveData data)
        {
            if (data.IsServer || m_clientToServerConnection.IsCreated)
            {
                return;
            }
            // Create a NetworkDriver for the client. We could bind to a specific address but in this case we rely on the
            // implicit bind since we do not need to bing to anything special
            m_ClientDriver = new UdpNetworkDriver(new INetworkParameter[0]);
            DebugManager.Instance.Print("Server address: " + data.Ip.ToString());
            NetworkEndPoint ServerEndPoint = NetworkEndPoint.Parse(data.Ip.ToString(), 9100);

            m_clientToServerConnection = m_ClientDriver.Connect(ServerEndPoint);
            DebugManager.Instance.Print("Connections status: " + m_clientToServerConnection.IsCreated);
        }
コード例 #25
0
 //////////////////////////////////
 /////// Client functions /////////
 public bool ConnectToServer(string ip = "", ushort port = 0)
 {
     try{
         if (string.IsNullOrEmpty(ip))
         {
             m_clientToServerConnection[0] = m_ClientDriver.Connect(GenerateNetworkEndPoint());
         }
         else
         {
             if (port == 0)
             {
                 m_clientToServerConnection[0] = m_ClientDriver.Connect(GenerateNetworkEndPoint(ip));
             }
             else
             {
                 m_clientToServerConnection[0] = m_ClientDriver.Connect(GenerateNetworkEndPoint(ip, port));
             }
         }
         return(true);
     }catch (System.Exception e) {
         TimeLogger.Log("CLIENT connection failure {0}", e.ToString());
         return(false);
     }
 }
コード例 #26
0
    public void Execute()
    {
        // If the client ui indicates we should be sending pings but we do not have an active connection we create one
        if (serverEP.IsValid && !connection[0].IsCreated)
        {
            connection[0] = driver.Connect(serverEP);
        }

        // If the client ui indicates we should not be sending pings but we do have a connection we close that connection
        if (!serverEP.IsValid && connection[0].IsCreated)
        {
            connection[0].Disconnect(driver);
            connection[0] = default(NetworkConnection);
        }
    }
コード例 #27
0
ファイル: SocketTests.cs プロジェクト: zs782306174/DOTSSample
        //[Ignore("https://favro.com/organization/c564ede4ed3337f7b17986b6/215d676dd474c0744d2574f8?card=Uni-90284")]
        public void UdpC_Timeout_ShouldDisconnect()
        {
            int customTimeout = 1000;

            var config = new NetworkConfigParameter {
                maxConnectAttempts  = NetworkParameterConstants.MaxConnectAttempts,
                connectTimeoutMS    = NetworkParameterConstants.ConnectTimeoutMS,
                disconnectTimeoutMS = customTimeout,
            };

            using (var server = new UdpNetworkDriver(config))
                using (var client = new UdpNetworkDriver(config))
                {
                    var serverPort = 50006;

                    server.Bind(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));
                    client.Bind(NetworkEndPoint.LoopbackIpv4);

                    server.Listen();

                    var id = client.Connect(NetworkEndPoint.CreateIpv4(0x7f000001, (ushort)serverPort));

                    NetworkConnection serverConnection, clientConnection;
                    int maxIterations = 100;

                    ConnectTogether(server, client, maxIterations, out serverConnection, out clientConnection);
                    Assert.AreEqual(id, serverConnection);

                    // Force timeout
                    Thread.Sleep(customTimeout + 500);

                    var message = new DataStreamWriter(7, Allocator.Persistent);
                    message.Write((byte)'m');
                    message.Write((byte)'e');
                    message.Write((byte)'s');
                    message.Write((byte)'s');
                    message.Write((byte)'a');
                    message.Write((byte)'g');
                    message.Write((byte)'e');
                    clientConnection.Send(server, message);

                    var data = new byte[1472];
                    int size = -1;
                    NetworkConnection from;
                    Assert.AreEqual(ExperimentalEventType.Disconnect, PollEvent(ExperimentalEventType.Disconnect, maxIterations, server, ref data, out size, out from));
                    Assert.AreEqual(from, clientConnection);
                }
        }
コード例 #28
0
            public void Execute()
            {
                // If the client ui indicates we should be sending pings but we do not have an active connection we create one
                if (!connection[0].IsCreated)
                {
                    //Debug.Log(@"serverEP.IsValid && !connection[0].IsCreated");
                    connection[0] = driver.Connect(serverEp);
                }

                NetworkEvent.Type cmd;
                disconnected[0] = false;

                // Process all events on the connection. If the connection is invalid it will return Empty immediately
                while ((cmd = connection[0].PopEvent(driver, out var pingStream)) != NetworkEvent.Type.Empty)
                {
                    switch (cmd)
                    {
                    case NetworkEvent.Type.Connect:
                        // Terminate the server by sending a value of -1
                        var pingData = new DataStreamWriter(4, Allocator.Temp);
                        pingData.Write(-1);
                        connection[0].Send(driver, pingData);
                        break;

                    case NetworkEvent.Type.Data:
                        // Confirm the termination code was echoed
                        var readerCtx = default(DataStreamReader.Context);
                        var id        = pingStream.ReadInt(ref readerCtx);

                        if (id != -1)
                        {
                            Debug.LogWarning($"Expected server to send back termination signal, but received {id} instead");
                        }

                        // Disconnect after sending termination code
                        connection[0].Disconnect(driver);
                        connection[0]   = default;
                        disconnected[0] = true;
                        break;

                    case NetworkEvent.Type.Disconnect:
                        // If the server disconnected us we clear out connection
                        connection[0]   = default;
                        disconnected[0] = true;
                        break;
                    }
                }
            }
コード例 #29
0
        public void Execute()
        {
            // If the client ui indicates we should be sending pings but we do not have an active connection we create one
            if (serverEP.IsValid && !connection[0].IsCreated)
            {
                connection[0] = driver.Connect(serverEP);
            }
            // If the client ui indicates we should not be sending pings but we do have a connection we close that connection
            if (!serverEP.IsValid && connection[0].IsCreated)
            {
                connection[0].Disconnect(driver);
                connection[0] = 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 = connection[0].PopEvent(driver, 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
                    pendingPings[0] = new PendingPing {
                        id = pingStats[0], time = fixedTime
                    };
                    // Create a 4 byte data stream which we can store our ping sequence number in
                    var pingData = new DataStreamWriter(4, Allocator.Temp);
                    pingData.Write(pingStats[0]);
                    connection[0].Send(driver, pingData);
                    // Update the number of sent pings
                    pingStats[0] = pingStats[0] + 1;
                }
                else if (cmd == NetworkEvent.Type.Data)
                {
                    // When the pong message is received we calculate the ping time and disconnect
                    pingStats[1] = (int)((fixedTime - pendingPings[0].time) * 1000);
                    connection[0].Disconnect(driver);
                    connection[0] = default(NetworkConnection);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    // If the server disconnected us we clear out connection
                    connection[0] = default(NetworkConnection);
                }
            }
        }
コード例 #30
0
    void Start()
    {
        m_Driver     = new UdpNetworkDriver(new INetworkParameter[0]);
        m_Connection = new NativeArray <NetworkConnection>(1, Allocator.Persistent);
        m_Done       = new NativeArray <byte>(1, Allocator.Persistent);
        m_Done[0]    = 0;

        m_Connection[0] = default(NetworkConnection);

        NetworkEndPoint client_endpoint = NetworkEndPoint.LoopbackIpv4;

        client_endpoint.Port = 9000;
        m_Connection[0]      = m_Driver.Connect(client_endpoint);
        cts = new Serializer <CustomType>();
        cts.Initialize();
    }