コード例 #1
0
ファイル: SocketTests.cs プロジェクト: zs782306174/DOTSSample
        void ConnectTogether(UdpNetworkDriver server, UdpNetworkDriver client, int maxIterations, out NetworkConnection serverConnection, out NetworkConnection clientConnection)
        {
            int servers = 0, clients = 0, iterations = 0;

            serverConnection = default(NetworkConnection);
            clientConnection = default(NetworkConnection);

            DataStreamReader reader;

            NetworkConnection poppedConnection = default(NetworkConnection);

            while (clients != 1 || servers != 1)
            {
                Assert.Less(iterations++, maxIterations);

                server.ScheduleUpdate().Complete();

                var newConnection = server.Accept();
                if (newConnection != default(NetworkConnection))
                {
                    clients++;
                    clientConnection = newConnection;
                }

                if (client.PopEvent(out poppedConnection, out reader) == ExperimentalEventType.Connect)
                {
                    serverConnection = poppedConnection;
                    servers++;
                }

                client.ScheduleUpdate().Complete();
                Assert.AreNotEqual(clientConnection, default(NetworkConnection));
            }
        }
コード例 #2
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");
        }
コード例 #3
0
        public void Execute()
        {
            // Remove connections which have been destroyed from the list of active connections
            for (int i = 0; i < connections.Length; ++i)
            {
                if (!connections[i].IsCreated)
                {
                    connections.RemoveAtSwapBack(i);
                    // Index i is a new connection since we did a swap back, check it again
                    --i;
                }
            }

            // Accept all new connections
            while (true)
            {
                var con = driver.Accept();
                // "Nothing more to accept" is signaled by returning an invalid connection from accept
                if (!con.IsCreated)
                {
                    break;
                }
                connections.Add(con);
            }
        }
コード例 #4
0
    void AcceptConnections()
    {
        //  Accepts the new Connections
        NetworkConnection connection;

        while ((connection = Driver.Accept()) != default(NetworkConnection))
        {
            Connections.Add(connection);
            //players.Add(new ClientPlayer(connection.GetHashCode()));
            //Debug.Log($"Player Id: {connection.GetHashCode()}");
            Debug.Log("Server: Accepted a connection");

            using (DataStreamWriter writer = new DataStreamWriter(16, Allocator.Temp))
            {
                writer.Write((int)ServerDataType.IdAssignment);
                writer.Write(IdCount);
                Driver.Send(NetworkPipeline.Null, connection, writer);

                Debug.Log($"Server: Sent client id: {IdCount}");
            }

            Vector3    spawnPos = new Vector3(0.0f, 4.0f, 0.0f);
            Quaternion spawnRot = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);

            ClientObjects.Add(IdCount, Instantiate(PlayerPreFab, spawnPos, spawnRot));
            ClientObjectFired.Add(IdCount, new FiredBool());

            IdCount++;
        }
    }
コード例 #5
0
            public void Execute()
            {
                NetworkConnection con;

                while ((con = driver.Accept()) != default(NetworkConnection))
                {
                    // New connection can never have any events, if this one does - just close it
                    DataStreamReader reader;
                    if (con.PopEvent(driver, out reader) != NetworkEvent.Type.Empty)
                    {
                        con.Disconnect(driver);
                        continue;
                    }

                    // create an entity for the new connection
                    var ent = commandBuffer.CreateEntity();
                    commandBuffer.AddComponent(ent, new NetworkStreamConnection {
                        Value = con
                    });
                    commandBuffer.AddComponent(ent, new NetworkSnapshotAckComponent());
                    commandBuffer.AddComponent(ent, new CommandTargetComponent());
                    commandBuffer.AddBuffer <IncomingRpcDataStreamBufferComponent>(ent);
                    commandBuffer.AddBuffer <OutgoingRpcDataStreamBufferComponent>(ent);
                    commandBuffer.AddBuffer <IncomingCommandDataStreamBufferComponent>(ent);
                    commandBuffer.AddBuffer <IncomingSnapshotDataStreamBufferComponent>(ent);
                }
            }
コード例 #6
0
    public void Execute()
    {
        // Remove connections which have been destroyed from the list of active connections
        for (int i = 0; i < connections.Length; ++i)
        {
            if (!connections[i].IsCreated)
            {
                connections.RemoveAtSwapBack(i);
                // Index i is a new connection since we did a swap back, check it again
                --i;
            }
        }

        // Accept all new connections when server is on SET UP state
        if (serverState == ServerController.ServerState.SetUp)
        {
            while (true)
            {
                NetworkConnection con = driver.Accept();
                // "Nothing more to accept" is signaled by returning an invalid connection from accept
                if (con.IsCreated)
                {
                    // TimeLogger.Log("SERVER - new connection - [{0}]", con.InternalId);
                    connections.Add(con);
                }
                else
                {
                    break;
                }
            }
        }
    }
コード例 #7
0
    // Update is called once per frame
    private void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

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

        // Accept new connections
        NetworkConnection connection;

        while ((connection = m_Driver.Accept()) != default(NetworkConnection))
        {
            m_Connections.Add(connection);
            Debug.Log("Accepted a connection");
        }

        DataStreamReader stream;

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

            NetworkEvent.Type cmd;

            while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    var  readerCtx = default(DataStreamReader.Context);
                    uint number    = stream.ReadUInt(ref readerCtx);

                    Debug.Log("Got " + number + " from the client adding + 2 to it and sending it back.");

                    number += 2;

                    using (var writer = new DataStreamWriter(4, Allocator.Temp))
                    {
                        writer.Write(number);
                        m_Driver.Send(m_Pipeline, m_Connections[i], writer);
                    }
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log("Client disconnected from the server.");
                    m_Connections[i] = default;
                }
            }
        }
    }
コード例 #8
0
ファイル: Server.cs プロジェクト: aaronvark/KGDEV4-Examples
    // Update is called once per frame
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

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

        // Accept new connections
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            m_Connections.Add(c);
            Debug.Log("Accepted a connection");
        }

        DataStreamReader stream;

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

            NetworkEvent.Type cmd;
            while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) !=
                   NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    //read received packet
                    DataStreamReader.Context readerCtx = default(DataStreamReader.Context);
                    PacketFunctions.ReadPacket(stream, ref readerCtx);

                    StartCoroutine(SendHelloClient(m_Connections[i]));

                    /*
                     * var readerCtx = default(DataStreamReader.Context);
                     * uint number = stream.ReadUInt(ref readerCtx);
                     * using (var writer = new DataStreamWriter(4, Allocator.Temp))
                     * {
                     *  writer.Write(number);
                     *  //other option
                     *  //m_Connections[i].Send(m_Driver, writer);
                     *  m_Driver.Send(NetworkPipeline.Null, m_Connections[i], writer);
                     * }
                     */
                }
            }
        }
    }
コード例 #9
0
        private void Update()
        {
            m_Driver.ScheduleUpdate().Complete();

            // CleanUpConnections
            for (int i = 0; i < m_Connections.Length; i++)
            {
                if (!m_Connections[i].IsCreated)
                {
                    Debug.Log($"Connection {i} has been cleaned up");
                    m_Connections.RemoveAtSwapBack(i);
                    --i;
                }
            }

            NetworkConnection c;

            while ((c = m_Driver.Accept()) != default(NetworkConnection))
            {
                Debug.Log($"New user connected: {c.InternalId}");

                m_Connections.Add(c);
                ClientConnected(c);
                OnClientConnected?.Invoke(c);
            }

            DataStreamReader stream;

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

                NetworkEvent.Type cmd;

                var readerCtx = default(DataStreamReader.Context);

                while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty)
                {
                    if (cmd == NetworkEvent.Type.Data)
                    {
                        Read(i, stream, ref readerCtx);
                    }
                    else if (cmd == NetworkEvent.Type.Disconnect)
                    {
                        Debug.Log("Client disconnected from server");
                        m_Connections[i] = default(NetworkConnection);
                        ClientDisconnected(m_Connections[i].InternalId);
                        OnClientDisconnected?.Invoke(m_Connections[i].InternalId);
                    }
                }
            }

            OnUpdate();
        }
コード例 #10
0
ファイル: LANServer.cs プロジェクト: Pjchardt/lan_multiplayer
        void FixedUpdate()
        {
            if (!m_ServerDriver.IsCreated)
            {
                return;
            }

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

            // Accept all new connections
            while (true)
            {
                var con = m_ServerDriver.Accept();
                // "Nothing more to accept" is signaled by returning an invalid connection from accept
                if (!con.IsCreated)
                {
                    break;
                }
                m_connections.Add(con);
            }

            for (int i = 0; i < m_connections.Length; ++i)
            {
                DataStreamReader  strm;
                NetworkEvent.Type cmd;
                // Pop all events for the connection
                while ((cmd = m_ServerDriver.PopEventForConnection(m_connections[i], out strm)) != NetworkEvent.Type.Empty)
                {
                    if (cmd == NetworkEvent.Type.Data)
                    {
                        // For ping requests we reply with a pong message
                        // A DataStreamReader.Context is required to keep track of current read position since
                        // DataStreamReader is immutable
                        var readerCtx = default(DataStreamReader.Context);
                        int id        = strm.ReadInt(ref readerCtx);
                        // Create a temporary DataStreamWriter to keep our serialized pong message
                        var pongData = new DataStreamWriter(4, Allocator.Temp);
                        pongData.Write(id);
                        // Send the pong message with the same id as the ping
                        m_ServerDriver.Send(NetworkPipeline.Null, m_connections[i], pongData);
                    }
                    else if (cmd == NetworkEvent.Type.Disconnect)
                    {
                        // This connection no longer exist, remove it from the list
                        // The next iteration will operate on the new connection we swapped in so as long as it exist the
                        // loop can continue
                        m_connections.RemoveAtSwapBack(i);
                        if (i >= m_connections.Length)
                        {
                            break;
                        }
                    }
                }
            }
        }
コード例 #11
0
        //Accepts new network connections
        void acceptNewConnections()
        {
            NetworkConnection newConnection;

            while ((newConnection = networkDriver.Accept()) != default(NetworkConnection))
            {
                networkConnections.Add(newConnection); //Add new connection to active connections
                Debug.Log("Accepted a connection");
            }
        }
コード例 #12
0
    private void AddNewConnections()
    {
        // Accept new connections
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            m_Connections.Add(c);
            Debug.Log("Accepted a connection");
        }
    }
コード例 #13
0
    private void AcceptNewConnectionsAndCreateGames()
    {
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            PlaceToWaitingList(c);
            Debug.Log("Accepted a connection");
        }

        BuildGamesFromWaitingList();
    }
コード例 #14
0
    private void AcceptNewConnections()
    {
        NetworkConnection c;

        while ((c = driver.Accept()) != default(NetworkConnection))
        {
            connections.Add(c);
            clientTimers.Add(0);
            clientMessages.Add("0-0-0-0");
            clientPositions.Add(Vector2.zero);
            Debug.Log("New client connected.");
        }
    }
コード例 #15
0
        /// <summary>
        /// Accepts new network connections.
        /// </summary>
        private void acceptNewConnections()
        {
            NetworkConnection newConnection;

            while ((newConnection = networkDriver.Accept()) != default)
            {
                networkConnections.Add(newConnection); //Add new connection to active connections

                Debug.Log("<color=magenta><b>[Server]</b></color> Accepted a connection.");

                assignClientID(newConnection);
            }
        }
コード例 #16
0
        public void Execute()
        {
            //Debug.Log("listen for connections job");
            NetworkConnection connection;

            while ((connection = driver.Accept()) != default(NetworkConnection))
            {
                Entity serverConnectionEntity = commandBuffer.CreateEntity();
                commandBuffer.AddComponent(serverConnectionEntity, new NetworkServerConnection {
                    connection = connection
                });
                Debug.Log("connection accepted");
            }
        }
コード例 #17
0
            public void Execute()
            {
                NetworkConnection con;

                while ((con = driver.Accept()) != default(NetworkConnection))
                {
                    // New connection can never have any events, if this one does - just close it
                    DataStreamReader reader;
                    if (con.PopEvent(driver, out reader) != NetworkEvent.Type.Empty)
                    {
                        con.Disconnect(driver);
                        continue;
                    }

                    // create an entity for the new connection
                    var ent = commandBuffer.CreateEntity();
                    commandBuffer.AddComponent(ent, new NetworkStreamConnection {
                        Value = con
                    });
                    commandBuffer.AddComponent(ent, new NetworkSnapshotAckComponent());
                    commandBuffer.AddComponent(ent, new CommandTargetComponent());
                    commandBuffer.AddBuffer <IncomingRpcDataStreamBufferComponent>(ent);
                    var rpcBuffer = commandBuffer.AddBuffer <OutgoingRpcDataStreamBufferComponent>(ent);
                    commandBuffer.AddBuffer <IncomingCommandDataStreamBufferComponent>(ent);
                    commandBuffer.AddBuffer <IncomingSnapshotDataStreamBufferComponent>(ent);

                    RpcSystem.SendProtocolVersion(rpcBuffer, protocolVersion);

                    // Send RPC - assign network id
                    int nid;
                    if (!freeNetworkIds.TryDequeue(out nid))
                    {
                        // Avoid using 0
                        nid             = numNetworkId[0] + 1;
                        numNetworkId[0] = nid;
                    }

                    commandBuffer.AddComponent(ent, new NetworkIdComponent {
                        Value = nid
                    });
                    rpcQueue.Schedule(rpcBuffer, new RpcSetNetworkId
                    {
                        nid         = nid,
                        netTickRate = tickRate.NetworkTickRate,
                        simMaxSteps = tickRate.MaxSimulationStepsPerFrame,
                        simTickRate = tickRate.SimulationTickRate
                    });
                }
            }
コード例 #18
0
        public void Execute()
        {
            // Clean up connections
            for (int i = 0; i < R_ExistingConnections.Length; i++)
            {
                if (!R_ExistingConnections[i].Connection.IsCreated)
                {
                    RW_CommandBuffer.DestroyEntity(R_ExistingConnectionsEntities[i]);
                }
            }
            // Accept new connections
            NetworkConnection c;

            while ((c = RW_Driver.Accept()) != default(NetworkConnection))
            {
                Entity t_ConnectionToClient = RW_CommandBuffer.CreateEntity(R_ServerConnectionArchetype);
                RW_CommandBuffer.SetComponent(t_ConnectionToClient, new C_NetworkConnection
                {
                    Connection = c
                });
                RW_CommandBuffer.AddComponent <C_PlayerIndex>(t_ConnectionToClient);
                RW_CommandBuffer.SetComponent(t_ConnectionToClient, new C_PlayerIndex
                {
                    PlayerId = c.InternalId
                });
                RW_CommandBuffer.AddComponent <C_PlayerPos>(t_ConnectionToClient);
                Vector2Int t_StartingPos = default;
                switch (c.InternalId)
                {
                case 0:
                    t_StartingPos = new Vector2Int(0, 0);
                    break;

                case 1:
                    t_StartingPos = new Vector2Int(R_GridDefinitions.RowCount - 1, R_GridDefinitions.ColumnCount - 1);
                    break;

                default:
                    break;
                }
                RW_CommandBuffer.SetComponent(t_ConnectionToClient, new C_PlayerPos
                {
                    Pos = t_StartingPos
                });

                Debug.Log($"Accepted a connection and placed new player {c.InternalId} at {t_StartingPos}");
            }
        }
コード例 #19
0
 public void Execute()
 {
     // Accept all connections and create entities for the new connections using an entity command buffer
     while (true)
     {
         var con = driver.Accept();
         if (!con.IsCreated)
         {
             break;
         }
         var ent = commandBuffer.CreateEntity();
         commandBuffer.AddComponent(ent, new PingServerConnectionComponentData {
             connection = con
         });
     }
 }
コード例 #20
0
    void NewConnect()
    {
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            var currentPlayer = Player.NewPlayer(c.InternalId);
            if (Connections.Length > 0)
            {
                SendNewChallenger(currentPlayer);
            }
            Connections.Add(c);
            m_Players.Add(c.InternalId, currentPlayer);
            SendFirstUpdateMessage(c);
        }
    }
コード例 #21
0
            public void Execute()
            {
                Unity.Networking.Transport.NetworkConnection connection;
                while ((connection = driver.Accept()) != default)
                {
                    // New connection can never have any events, if this one does - just close it
                    DataStreamReader reader;
                    if (connection.PopEvent(driver, out reader) != NetworkEvent.Type.Empty)
                    {
                        //connection.Disconnect(driver);
#if UNITY_EDITOR
                        Debug.LogError("connection.PopEvent(driver, out reader) != NetworkEvent.Type.Empty");
#endif


                        var entity = endCommandBuffer.CreateEntity();
                        endCommandBuffer.AddComponent(entity, new NetworkConnection {
                            value = connection
                        });

                        endCommandBuffer.AddComponent(entity, new NetworkConnectedMessage {
                        });
                        endCommandBuffer.AddComponent(entity, new NetworkDisconnectedMessage {
                            error = (short)DisconnectedErrors.Accept
                        });

                        //endCommandBuffer.RemoveComponent<NetworkConnectedMessage>(entity);//这里的entity不能跨CommandBuffer使用
                        //endCommandBuffer.RemoveComponent<NetworkDisconnectedMessage>(entity);//这里的entity不能跨CommandBuffer使用
                    }
                    else
                    {
                        // create an entity for the new connection
                        var entity = endCommandBuffer.CreateEntity();
                        endCommandBuffer.AddComponent(entity, new NetworkConnection {
                            value = connection
                        });

                        endCommandBuffer.AddComponent(entity, NetworkInBuffer);
                        endCommandBuffer.AddComponent(entity, NetworkReliableOutBuffer);
                        endCommandBuffer.AddComponent(entity, NetworkUnreliableOutBuffer);

                        endCommandBuffer.AddComponent(entity, new NetworkConnectedMessage {
                        });
                        //endCommandBuffer.RemoveComponent<NetworkConnectedMessage>(entity);//这里的entity不能跨CommandBuffer使用
                    }
                }
            }
コード例 #22
0
    public void Execute()
    {
        // CleanUpConnections
        for (int i = 0; i < connections.Length; i++)
        {
            if (!connections[i].IsCreated)
            {
                connections.RemoveAtSwapBack(i);
                --i;
            }
        }
        // AcceptNewConnections
        NetworkConnection c;

        while ((c = driver.Accept()) != default(NetworkConnection))
        {
            connections.Add(c);
            Debug.Log("Accepted a connection");
        }
    }
コード例 #23
0
    public void Execute()
    {
        for (int i = 0; i < connections.Length; i++)
        {
            if (!connections[i].Connection.IsCreated)
            {
                connections.RemoveAtSwapBack(i);
                --i;
            }
        }

        NetworkConnection c;

        while ((c = driver.Accept()) != default(NetworkConnection))
        {
            connections.Add(new SoakClientCtx {
                Connection = c, NextSequenceId = now
            });
        }
    }
コード例 #24
0
    public void Execute()
    {
        // Clean up connections
        for (int i = 0; i < connections.Length; i++)
        {
            if (!connections[i].IsCreated)
            {
                connections.RemoveAtSwapBack(i);
                --i;
            }
        }
        // Accept new connections
        NetworkConnection c;

        while ((c = driver.Accept()) != default(NetworkConnection))
        {
            Debug.Log("Accepted a connection");
            // spawn new player and have its name be the same as its index in connections/players
            // create new player information to keep track of this player
        }
    }
コード例 #25
0
    void AcceptNewConnections()
    {
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            Debug.Log("[SERVER] Accepted a connection with the following data: ");
            Debug.Log("[SERVER] InternalId: " + c.InternalId);

            var currentPlayer = Player.NewPlayer(c.InternalId);
            Debug.Log("Tell other players of this new player");
            if (m_Connections.Length > 0)
            {
                SendNewChallenger(currentPlayer);
            }
            Debug.Log("[SERVER] Before adding new client to the list of connections and dictionary of game obejcts");
            m_Connections.Add(c);
            m_Players.Add(c.InternalId, currentPlayer);
            Debug.Log("[SERVER] About to send info about exisitng players to the guy");
            SendFirstUpdateMessage(c);
        }
    }
コード例 #26
0
    public void Execute()
    {
        //  cleanes up old state connections
        //  before processing new ones
        for (int connection_i = 0; connection_i < connections.Length; connection_i++)
        {
            if (!connections[connection_i].IsCreated)
            {
                connections.RemoveAtSwapBack(connection_i);
                --connection_i;
            }
        }

        //  Accepts the new connections
        NetworkConnection connection;

        while ((connection = driver.Accept()) != default(NetworkConnection))
        {
            connections.Add(connection);
            players.Add(new ClientPlayer(connection.GetHashCode()));
            Debug.Log($"Player Id: {connection.GetHashCode()}");
            Debug.Log("Accepted a connection");
        }
    }
コード例 #27
0
    void AcceptConnections()
    {
        Debug.Log($"Server: Accepting Connections");

        //  Accepts the new Connections
        NetworkConnection connection;

        while ((connection = Driver.Accept()) != default(NetworkConnection))
        {
            Connections.Add(connection);
            //players.Add(new ClientPlayer(connection.GetHashCode()));
            //Debug.Log($"Player Id: {connection.GetHashCode()}");
            Debug.Log("Server: Accepted a connection");

            using (DataStreamWriter writer = new DataStreamWriter(16, Allocator.Temp))
            {
                writer.Write((int)ServerDataType.IdAssignment);
                writer.Write(IdCount);
                Driver.Send(NetworkPipeline.Null, connection, writer);

                Debug.Log($"Server: Sent client id: {IdCount}");
            }

            Vector3    spawnPos = new Vector3(0.0f, 4.0f, 0.0f);
            Quaternion spawnRot = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);

            ClientState newState = new ClientState();
            newState.PlayerPosition = spawnPos;
            newState.PlayerRotation = spawnRot;
            newState.Health         = 10;

            ClientStates.Add(IdCount, newState);

            IdCount++;
        }
    }
コード例 #28
0
    void FixedUpdate()
    {
        // Update the NetworkDriver. It schedules a job so we must wait for that job with Complete
        m_ServerDriver.ScheduleUpdate().Complete();

        // Accept all new connections
        while (true)
        {
            var con = m_ServerDriver.Accept();
            // "Nothing more to accept" is signaled by returning an invalid connection from accept
            if (!con.IsCreated)
            {
                break;
            }
            m_connections.Add(con);
            // Debug.Log("Connected is " + con.InternalId);
            // var idData = new DataStreamWriter(4, Allocator.Temp);
            //  idData.Write(con.InternalId);
            // DataStreamReader strm;

            // m_ServerDriver.PopEventForConnection(con, out strm);
            //m_ServerDriver.Send(NetworkPipeline.Null, con, idData);
        }
        List <Player> clientList = ServerManager.GetClients();

        for (int i = 0; i < m_connections.Length; ++i)
        {
            DataStreamReader  strm;
            NetworkEvent.Type cmd;
            // Pop all events for the connection
            while ((cmd = m_ServerDriver.PopEventForConnection(m_connections[i], out strm)) != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    var  readerCtx = default(DataStreamReader.Context);
                    byte data      = strm.ReadByte(ref readerCtx);
                    CMD  command   = (CMD)data;
                    switch (command)
                    {
                    case CMD.CONNECT:
                        var id = ServerManager.RegisterPlayer(m_connections[i].InternalId);
                        Debug.Log("Connected " + id);
                        byte[] idData = NetworkLayer.newCommand(CMD.CONNECT, BitConverter.GetBytes(id));
                        var    newID  = new DataStreamWriter(idData.Length, Allocator.Temp);
                        newID.Write(idData);
                        m_ServerDriver.Send(NetworkPipeline.Null, m_connections[i], newID);
                        break;

                    case CMD.PLAYER_UPDATE:
                        byte[] playerByte = strm.ReadBytesAsArray(ref readerCtx, 32);
                        var    player     = ByteConverter.toPlayer(playerByte);
                        ServerManager.OnUpdatePlayer(player);
                        break;

                    case CMD.SHOOT:
                        var shootBye  = NetworkLayer.newCommand(CMD.SHOOT, BitConverter.GetBytes(m_connections[i].InternalId));
                        var shootData = new DataStreamWriter(shootBye.Length, Allocator.Temp);
                        shootData.Write(shootBye);
                        for (int y = 0; y < m_connections.Length; ++y)
                        {
                            if (m_connections[i] != m_connections[y])
                            {
                                m_ServerDriver.Send(NetworkPipeline.Null, m_connections[y], shootData);
                            }
                        }
                        ;
                        break;

                    case CMD.PLAYER_DIE:
                        Debug.LogWarning(" S DIE");
                        var dieByte = NetworkLayer.newCommand(CMD.PLAYER_DIE, BitConverter.GetBytes(m_connections[i].InternalId));
                        var dieData = new DataStreamWriter(dieByte.Length, Allocator.Temp);
                        dieData.Write(dieByte);
                        for (int y = 0; y < m_connections.Length; ++y)
                        {
                            m_ServerDriver.Send(NetworkPipeline.Null, m_connections[y], dieData);
                        }
                        ;
                        break;
                    }
                    for (int clientIndex = 0; clientIndex < clientList.Count; clientIndex++)
                    {
                        byte[] playerData = NetworkLayer.newCommand(CMD.PLAYER_UPDATE, ByteConverter.playerToByte(clientList[clientIndex]));
                        var    player     = new DataStreamWriter(playerData.Length, Allocator.Temp);
                        player.Write(playerData);
                        m_ServerDriver.Send(NetworkPipeline.Null, m_connections[i], player);
                    }
                    ;

                    // Send the pong message with the same id as the ping
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    // This connection no longer exist, remove it from the list
                    // The next iteration will operate on the new connection we swapped in so as long as it exist the
                    // loop can continue
                    Debug.Log("Desconnected " + m_connections[i].InternalId);
                    byte[] disconnectData = NetworkLayer.newCommand(CMD.PLAYER_DISCONNECTED, BitConverter.GetBytes(m_connections[i].InternalId));
                    var    player         = new DataStreamWriter(disconnectData.Length, Allocator.Temp);
                    player.Write(disconnectData);
                    ServerManager.OnDisconnectPlayer(m_connections[i].InternalId);
                    m_connections.RemoveAtSwapBack(i);
                    for (int y = 0; y < m_connections.Length; ++y)
                    {
                        m_ServerDriver.Send(NetworkPipeline.Null, m_connections[y], player);
                    }
                    ;
                    if (i >= m_connections.Length)
                    {
                        break;
                    }
                }
            }
        }
    }
コード例 #29
0
        public IEnumerator ServerAnd5Clients_Connect_Successfully()
        {
            int numberOfClients = 5;
            NativeArray <NetworkConnection> connectionToClientArray;

            UdpNetworkDriver[] client_driversArray = new UdpNetworkDriver[numberOfClients];
            NativeArray <NetworkConnection> clientToServerConnectionsArray;

            //setup server
            connectionToClientArray = new NativeArray <NetworkConnection>(numberOfClients, Allocator.Persistent);
            server_driver           = new UdpNetworkDriver(new NetworkDataStreamParameter {
                size = 0
            });
            NetworkEndPoint server_endpoint = NetworkEndPoint.LoopbackIpv4;

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

            //setup clients
            clientToServerConnectionsArray = new NativeArray <NetworkConnection>(numberOfClients, Allocator.Persistent);

            for (int i = 0; i < numberOfClients; i++)
            {
                client_driversArray[i] = new UdpNetworkDriver(new NetworkDataStreamParameter {
                    size = 0
                });
                clientToServerConnectionsArray[i] = client_driversArray[i].Connect(server_endpoint);
            }

            //update drivers
            for (int i = 0; i < numberOfClients; i++)
            {
                client_driversArray[i].ScheduleUpdate().Complete();
            }
            server_driver.ScheduleUpdate().Complete();

            //accept connections
            for (int i = 0; i < numberOfClients; i++)
            {
                connectionToClientArray[i] = server_driver.Accept();

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

                client_driversArray[i].ScheduleUpdate().Complete();
                ev = clientToServerConnectionsArray[i].PopEvent(client_driversArray[i], out stream);
                Assert.IsTrue(ev == NetworkEvent.Type.Connect, "NetworkEvent should have Type.Connect on the client");
            }
            //close connections
            for (int i = 0; i < numberOfClients; i++)
            {
                clientToServerConnectionsArray[i].Close(client_driversArray[i]);

                //update drivers
                client_driversArray[i].ScheduleUpdate().Complete();
                server_driver.ScheduleUpdate().Complete();

                ev = server_driver.PopEventForConnection(connectionToClientArray[i], out stream);
                Assert.IsTrue(ev == NetworkEvent.Type.Disconnect, "NetworkEvent.Type.Disconnect was expected to appear, but " + ev + "appeared");
            }

            server_driver.Dispose();
            for (int i = 0; i < numberOfClients; i++)
            {
                client_driversArray[i].Dispose();
            }
            connectionToClientArray.Dispose();
            clientToServerConnectionsArray.Dispose();

            yield return(null);
        }
コード例 #30
0
    private void Update()
    {
        if (!started)
        {
            return;
        }
        if (timer <= 25)
        {
            timer += Time.deltaTime;
        }
        else
        {
            timer = 0f;
            SendCmdToAllClients("LEER");
            Debug.Log("Sending empty to keep connection");
        }

        driver.ScheduleUpdate().Complete();

        for (int i = 0; i < connection.Length; i++)
        {
            if (!connection[i].IsCreated)
            {
                connection.RemoveAtSwapBack(i);
                Debug.LogError("is created abfrage 1");
                --i;
            }
        }

        NetworkConnection con;

        while ((con = driver.Accept()) != default(NetworkConnection))
        {
            connection.Add(con);
            string cmdString = "AUTHENTICATE|";
            SendCmdToClient(cmdString, con);
        }

        DataStreamReader sr;

        for (int i = 0; i < connection.Length; i++)
        {
            if (!connection[i].IsCreated)
            {
                Debug.LogError("created abfrage");
                continue;
            }


            NetworkEvent.Type cmd;
            while ((cmd = driver.PopEventForConnection(connection[i], out sr)) != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Connect)
                {
                    Debug.Log("client " + i + " has connected");
                }

                if (cmd == NetworkEvent.Type.Disconnect)
                {
                    playerHasDisconnected = true;
                    playerDic.Remove(FindKeyByConID(i));
                    for (int j = 0; j < connection.Length; j++)
                    {
                        if (j != i)
                        {
                        }
                    }
                }
                if (cmd == NetworkEvent.Type.Data)
                {
                    var    readerCtx = default(DataStreamReader.Context);
                    byte[] data      = sr.ReadBytesAsArray(ref readerCtx, sr.Length);
                    string cmdString = System.Text.Encoding.UTF8.GetString(data);
                    ProcessCmd(cmdString, i);
                }
            }
        }
    }