private void ReadIncomingMessages() { //Create reader DataStreamReader stream; //For each connection for (int i = 0; i < m_Connections.Length; i++) { //If there's more than one connection Assert.IsTrue(m_Connections[i].IsCreated); //Type of network event NetworkEvent.Type cmd; //Get event cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); //While event is not empty while (cmd != NetworkEvent.Type.Empty) { //If event data - if (cmd == NetworkEvent.Type.Data) { //Process events OnData(stream, i); } else if (cmd == NetworkEvent.Type.Disconnect) { //If type disconnect - disconnect OnDisconnect(i); } //Get an event cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } }
private void ReadIncomingMessages() { DataStreamReader stream; for (int i = 0; i < m_Connections.Length; i++) //Loop through all active connections { Assert.IsTrue(m_Connections[i].IsCreated); //Insure that the connection is valid. (ie. not a default connection) //Check type of connection and process it accordingly NetworkEvent.Type cmd; cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); while (cmd != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { // Fill the DataStreamReader stream with the data and send it to OnData(). i is index of the connection taking place OnData(stream, i); } else if (cmd == NetworkEvent.Type.Disconnect) { OnDisconnect(i); // Disconnect } cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } }
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(); } }
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 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); } } }
void Update() { m_Driver.ScheduleUpdate().Complete(); // Tell the driver we are ready to listen for next event // CleanUpConnections for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections[i].IsCreated) { m_Connections.RemoveAtSwapBack(i); --i; } } // AcceptNewConnections // Check if there is any new connection NetworkConnection c = m_Driver.Accept(); while (c != default(NetworkConnection)) { OnConnect(c); // Take the connection that just happeened and send to OnConnect c = m_Driver.Accept(); } // Read Incoming Messages DataStreamReader stream; for (int i = 0; i < m_Connections.Length; i++) { Assert.IsTrue(m_Connections[i].IsCreated); // Make sure a connection is valid (Should not be a default connection) NetworkEvent.Type cmd; cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); while (cmd != NetworkEvent.Type.Empty) // As long as the event type is not 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); } } }
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"); }
public unsafe void Assert_PopEventForConnection(NetworkConnection connection, NetworkEvent.Type evnt) { DataStreamReader reader; var retval = m_LocalDriver.PopEventForConnection(connection, out reader); Assert.True(retval == evnt); }
void ReceiveMessages() { int total = 0; for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections.IsCreated) //Check connection state { continue; } NetworkEvent.Type cmd; while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out DataStreamReader stream)) != NetworkEvent.Type.Empty) { //Receiving data from client if (cmd == NetworkEvent.Type.Data) { int num = stream.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); } } } }
void Update() { m_Driver.ScheduleUpdate().Complete(); //connection cleanup for (int i = 0; i < m_Connections.Length; ++i) { if (!m_Connections[i].IsCreated) { m_Connections.RemoveAtSwapBack(i); --i; } } //accepting new connections NetworkConnection c = m_Driver.Accept(); while (c != default(NetworkConnection)) { OnConnect(c); c = m_Driver.Accept(); } //Incoming messages reading DataStreamReader stream; for (int i = 0; i < m_Connections.Length; ++i) { Assert.IsTrue(m_Connections[i].IsCreated); NetworkEvent.Type eventType; eventType = m_Driver.PopEventForConnection(m_Connections[i], out stream); while (eventType != NetworkEvent.Type.Empty) { if (eventType == NetworkEvent.Type.Data) { OnData(stream, i); } else if (eventType == NetworkEvent.Type.Disconnect) { OnDisconnect(i); } eventType = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } }
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; } } } }
void Update() { m_Driver.ScheduleUpdate().Complete(); for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections[i].IsCreated) { m_Connections.RemoveAtSwapBack(i); --i; } } NetworkConnection c = m_Driver.Accept(); while (c != default(NetworkConnection)) { OnConnect(c); 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, i, m_Connections[i]); heartbeat[m_Connections[i].InternalId.ToString()] = Time.time; } else if (cmd == NetworkEvent.Type.Disconnect) { OnDisconnect(i); } cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } AssertHeartbeatTime(); }
void Update() { m_Driver.ScheduleUpdate().Complete(); // CleanUpConnections CleanClients(); // 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 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); } } }
private void Update() { m_Driver.ScheduleUpdate().Complete(); // CleanUp the Connections CleanupClients(); // Accept hte New Connections NetworkConnection c; while ((c = m_Driver.Accept()) != default(NetworkConnection)) { OnConnect(c); } DataStreamReader stream; for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections[i].IsCreated) { Assert.IsTrue(true); } NetworkEvent.Type cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); while (cmd != NetworkEvent.Type.Empty) { //Receiving Data from Client if (cmd == NetworkEvent.Type.Data) { OnData(stream, i); } else if (cmd == NetworkEvent.Type.Disconnect) { m_Connections[i] = default(NetworkConnection); continue; } cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } }
private void Update() { driver.ScheduleUpdate().Complete(); //Clean up old connections for (int i = 0; i < connections.Length; i++) { if (!connections[i].IsCreated) { connections.RemoveAtSwapBack(i); --i; //Go back because we removed an index } } //Accept new connection - returns an up-to-date connection list NetworkConnection connection; while ((connection = driver.Accept()) != default(NetworkConnection)) { connections.Add(connection); Debug.Log("Accepted a connection"); ServerSend.Welcome(connection, connection.InternalId, availableHexColors[connection.InternalId].ColorToUInt()); } //Start querying driver events that might have happened since the last update DataStreamReader reader; for (int i = 0; i < connections.Length; i++) { if (!connections[i].IsCreated) { continue; } NetworkEvent.Type cmd; while ((cmd = driver.PopEventForConnection(connections[i], out reader)) != NetworkEvent.Type.Empty) { //Process events if (cmd == NetworkEvent.Type.Data) { packetHandlers[reader.ReadUShort()](reader, connections[i]); //Handle disconnections } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected from server"); ServerSend.PlayerLeft(connections[i].InternalId); connections[i] = default(NetworkConnection); } } } }
private void Update() { m_Driver.ScheduleUpdate().Complete(); CleanupConnection(); if (m_Connections.Length >= 2) { timer += Time.deltaTime; } NetworkConnection c; while ((c = m_Driver.Accept()) != default(NetworkConnection)) { OnConnect(c); } DataStreamReader stream; for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections[i].IsCreated) { Assert.IsTrue(true); } NetworkEvent.Type cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); while (cmd != NetworkEvent.Type.Empty) { //When received data from client if (cmd == NetworkEvent.Type.Data) { OnData(stream, i); } cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream); } } }
NetworkEvent.Type PollDriverAndFindDataEvent(ref NetworkDriver driver, NetworkConnection connection, NetworkEvent.Type eventType, int maxRetryCount = 10) { for (int retry = 0; retry < maxRetryCount; ++retry) { driver.ScheduleUpdate().Complete(); ev = driver.PopEventForConnection(connection, out stream); if (ev == eventType || ev != NetworkEvent.Type.Empty) { return(ev); } } return(NetworkEvent.Type.Empty); }
void FixedUpdate() { localDriver.ScheduleUpdate().Complete(); // CleanUpConnections for (int i = 0; i < connections.Length; i++) { if (!connections[i].IsCreated) { connections.RemoveAtSwapBack(i); --i; } } // AcceptNewConnections NetworkConnection c; while ((c = localDriver.Accept()) != default(NetworkConnection)) { connections.Add(c); Debug.Log("Accepted a connection"); } DataStreamReader stream; for (int i = 0; i < connections.Length; i++) { Assert.IsTrue(connections[i].IsCreated); NetworkEvent.Type cmd; while ((cmd = localDriver.PopEventForConnection(connections[i], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { var json = stream.ReadString(); var writer = localDriver.BeginSend(NetworkPipeline.Null, connections[i]); writer.WriteString(json); localDriver.EndSend(writer); //TODO for test //if (Random.Range(0, 99) % 9 == 0) //{ // localDriver.Disconnect(connections[i]); //} } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected from server"); connections[i] = default(NetworkConnection); } } } }
void ServerUpdate() { // 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_serverConnections.Add(con); } for (int i = 0; i < m_serverConnections.Length; ++i) { DataStreamReader strm; NetworkEvent.Type cmd; // Pop all events for the connection while ((cmd = m_ServerDriver.PopEventForConnection(m_serverConnections[i], out strm)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { // For ping requests we reply with a pong message int id = strm.ReadInt(); // Create a temporary DataStreamWriter to keep our serialized pong message if (m_ServerDriver.BeginSend(m_serverConnections[i], out var pongData) == 0) { pongData.WriteInt(id); // Send the pong message with the same id as the ping m_ServerDriver.EndSend(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_serverConnections.RemoveAtSwapBack(i); if (i >= m_serverConnections.Length) { break; } } } } }
public 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; 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++) { Assert.IsTrue(m_Connections[i].IsCreated); NetworkEvent.Type cmd; while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { var str = ""; while (stream.Length > stream.GetBytesRead()) { str += stream.ReadString(); } ProcessMessage(str); } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected from server"); m_Connections[i] = default(NetworkConnection); } } } }
public void DisconnectAndCleanup() { clientToServerConnection.Close(client_driver); //update drivers client_driver.ScheduleUpdate().Complete(); server_driver.ScheduleUpdate().Complete(); ev = server_driver.PopEventForConnection(connectionToClient, out stream); Assert.IsTrue(ev == NetworkEvent.Type.Disconnect, "NetworkEvent.Type.Disconnect was expected to appear, but " + ev + "appeared"); server_driver.Dispose(); client_driver.Dispose(); }
public void CreateConnectPopAndClose_NetworkConnection_ToRemoteEndPoint() { var connection = Driver.Connect(RemoteDriver.LocalEndPoint()); Assert.That(connection.IsCreated); Driver.ScheduleUpdate().Complete(); RemoteDriver.ScheduleUpdate().Complete(); var remoteId = default(NetworkConnection); Assert.That((remoteId = RemoteDriver.Accept()) != default(NetworkConnection)); DataStreamReader reader; Driver.ScheduleUpdate().Complete(); Assert.That(connection.PopEvent(Driver, out reader) == NetworkEvent.Type.Connect); connection.Close(Driver); Driver.ScheduleUpdate().Complete(); RemoteDriver.ScheduleUpdate().Complete(); Assert.That( RemoteDriver.PopEventForConnection(remoteId, out reader) == NetworkEvent.Type.Disconnect); }
private void ReadConnections() { NetworkEvent.Type command; // Read Events. for (int i = 0; i < connections.Length; i++) { var connection = connections[i]; Assert.IsTrue(connection.IsCreated); while ((command = driver.PopEventForConnection(connection, out var reader)) != NetworkEvent.Type.Empty) { switch (command) { case NetworkEvent.Type.Data: var message = new Message(); message.Deserialize(ref reader); readMessage?.Invoke(connection, reader, message); break; // Let the other connections now which player has disconnected. case NetworkEvent.Type.Disconnect: var playerLeftMessage = new PlayerMessage(MessageID.nextID, MessageType.PlayerLeft, connection.InternalId); foreach (var otherConnection in connections) { if (otherConnection == connection) { continue; } Send(otherConnection, playerLeftMessage); } onConnectionDisconnected?.Invoke(connection); connections[i] = default; break; } } } }
protected virtual void UpdateMessagePump() { DataStreamReader stream; for (int i = 0; i < connections.Length; i++) { NetworkEvent.Type cmd; while ((cmd = driver.PopEventForConnection(connections[i], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { netMessageHandlerManager.OnMessageReceived(stream); } else if (cmd == NetworkEvent.Type.Disconnect) { Logs.Print($"A client disconnected"); connections[i] = default(NetworkConnection); messageSender.NotifyDisconnect(i); } } } }
public NetworkEvent.Type PopEvent(NetworkDriver driver, out DataStreamReader stream, out NetworkPipeline pipeline) { return(driver.PopEventForConnection(this, out stream, out pipeline)); }
public unsafe void Execute() { for (int index = 0; index < connections.Length; index++) { DataStreamReader stream; if (!connections[index].IsCreated) { continue; } NetworkEvent.Type cmd; while ((cmd = driver.PopEventForConnection(connections[index], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { // First byte is the messageType MessageType messageType = (MessageType)stream.ReadByte(); switch (messageType) { case MessageType.StartServer: { // Check if they are already connected or perhaps are already hosting, if so return if (HasPeer(index) || connectionIndexToRoomID.ContainsKey(index)) { return; } Client client = new Client { ConnectionId = index, IsServer = true, OutgoingBytes = 0, ConnectTime = DateTime.UtcNow }; Room room = new Room { RoomId = GenerateRoomId(), Server = client, }; rooms.Add(room); connectionIndexToRoomID.Add(index, room.RoomId); NativeList <byte> ipv6AddressBuffer = new NativeList <byte>(16, Allocator.Temp); NetworkEndPoint ipAddress = driver.RemoteEndPoint(connections[index]); if (ipAddress.Family == NetworkFamily.Ipv6) { string ipv6Address = ipAddress.Address.Split(':')[0]; foreach (string n in ipv6Address.Split('.')) { ipv6AddressBuffer.Add(Byte.Parse(n)); } } else if (ipAddress.Family == NetworkFamily.Ipv4) { string ipv4Address = ipAddress.Address.Split(':')[0]; foreach (byte b in new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255 }) { ipv6AddressBuffer.Add(b); } foreach (string n in ipv4Address.Split('.')) { ipv6AddressBuffer.Add(Byte.Parse(n)); } } else { // TODO: Throw wrong type ipv6AddressBuffer = default(NativeList <byte>); } ipAddress.SetRawAddressBytes(ipv6AddressBuffer, NetworkFamily.Ipv6); serverAddressToRoomID.Add(ipAddress.Address, room.RoomId); if (ServerBehaviour.Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Server started from " + ipAddress.Address); } DataStreamWriter writer; writer = driver.BeginSend(pipeline, connections[index]); // Write the message type writer.WriteByte((byte)MessageType.AddressReport); // Write the Connection Id writer.WriteInt(index); // TODO: Throw if address is not 16 bytes. It should always be // Write the address writer.WriteBytes(ipv6AddressBuffer); // Write the port writer.WriteUShort(ipAddress.Port); // Send connect to client driver.EndSend(writer); ipv6AddressBuffer.Dispose(); } break; case MessageType.ConnectToServer: { // Check if they are already connected or perhaps are already hosting, if so return if (HasPeer(index) || connectionIndexToRoomID.ContainsKey(index)) { return; } NativeArray <byte> addressBytes = new NativeArray <byte>(16, Allocator.Temp); stream.ReadBytes(addressBytes); ushort remotePort = stream.ReadUShort(); NetworkEndPoint endpoint = new NetworkEndPoint(); endpoint.SetRawAddressBytes(addressBytes, NetworkFamily.Ipv6); endpoint.Port = remotePort; if (ServerBehaviour.Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Connection requested to address " + endpoint.Address); } if (serverAddressToRoomID.ContainsKey(endpoint.Address)) { if (ServerBehaviour.Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Connection approved"); } // Get the room they want to join Room room = GetRoom(serverAddressToRoomID[endpoint.Address]); // Create a client for them Client client = new Client { ConnectionId = index, IsServer = false, OutgoingBytes = 0, ConnectTime = DateTime.UtcNow }; // Handle the connect HandleClientConnect(room, client); } } break; case MessageType.Data: { foreach (Room room in rooms) { if (HasPeer(room, index, out bool isServer)) { // Found a matching client in room if (isServer) { // The server is sending data int destination = stream.ReadInt(); // Safety check. Make sure who they want to send to ACTUALLY belongs to their room if (HasPeer(room, destination, out isServer) && !isServer) { Send(room, destination, index, stream); } } else { // A client is sending data Send(room, room.ServerConnectionId, index, stream); } } } } break; case MessageType.ClientDisconnect: { int clientConnectionId = stream.ReadInt(); if (ServerBehaviour.Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Client disconnect request"); } foreach (Room room in rooms) { if (room.ServerConnectionId == clientConnectionId && HandleClientDisconnect(room, clientConnectionId, true)) { // Only disconnect one. A peer can only be in 1 room break; } } } break; } } else if (cmd == NetworkEvent.Type.Disconnect) { Console.WriteLine("[INFO] Client disconnected from server"); connections[index] = default(NetworkConnection); } } } }
void Update() { networkJobHandle.Complete(); for (int i = 0; i < connections.Length; ++i) { if (!connections[i].IsCreated) { connections.RemoveAtSwapBack(i); --i; } } NetworkConnection c; while ((c = networkDriver.Accept()) != default) { connections.Add(c); Debug.Log("Accepted connection"); var colour = (Color32)Color.magenta; var message = new WelcomeMessage { PlayerID = c.InternalId, Colour = ((uint)colour.r << 24) | ((uint)colour.g << 16) | ((uint)colour.b << 8) | colour.a }; var writer = networkDriver.BeginSend(c); message.SerializeObject(ref writer); networkDriver.EndSend(writer); } DataStreamReader reader; for (int i = 0; i < connections.Length; ++i) { if (!connections[i].IsCreated) { continue; } NetworkEvent.Type cmd; while ((cmd = networkDriver.PopEventForConnection(connections[i], out reader)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { var messageType = (MessageHeader.MessageType)reader.ReadUShort(); switch (messageType) { case MessageHeader.MessageType.None: break; case MessageHeader.MessageType.NewPlayer: break; case MessageHeader.MessageType.Welcome: break; case MessageHeader.MessageType.SetName: var message = new SetNameMessage(); message.DeserializeObject(ref reader); messagesQueue.Enqueue(message); break; case MessageHeader.MessageType.RequestDenied: break; case MessageHeader.MessageType.PlayerLeft: break; case MessageHeader.MessageType.StartGame: break; case MessageHeader.MessageType.Count: break; default: break; } } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected"); connections[i] = default; } } } networkJobHandle = networkDriver.ScheduleUpdate(); ProcessMessagesQueue(); }
void Update() { networkJobHandle.Complete(); for (int i = 0; i < connections.Length; ++i) { if (!connections[i].IsCreated) { connections.RemoveAtSwapBack(i); --i; } } NetworkConnection newConnection; while ((newConnection = networkDriver.Accept()) != default) { if (connections.Length >= 4) { return; } connections.Add(newConnection); //Debug.Log("Accepted new connection"); //new player data is set //Color col = Random.ColorHSV(); Color col = ColorExtensions.colors[(ColorExtensions.RandomStartIndex + newConnection.InternalId) % ColorExtensions.colors.Length]; col.a = 1; var colour = (Color32)col; var playerID = newConnection.InternalId; var welcomeMessage = new WelcomeMessage { PlayerID = playerID, Colour = ((uint)colour.r << 24) | ((uint)colour.g << 16) | ((uint)colour.b << 8) | colour.a }; SendMessage(welcomeMessage, newConnection); //save it to list PlayerData newData = new PlayerData(); newData.color = colour; newData.playerIndex = playerID; if (serverDataHolder.players == null) { serverDataHolder.players = new List <PlayerData>(); } serverDataHolder.players.Add(newData); //Debug.Log("server data holder players count: " + serverDataHolder.players.Count); } DataStreamReader reader; for (int i = 0; i < connections.Length; ++i) { if (!connections[i].IsCreated) { continue; } NetworkEvent.Type cmd; while ((cmd = networkDriver.PopEventForConnection(connections[i], out reader)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { var messageType = (MessageHeader.MessageType)reader.ReadUShort(); switch (messageType) { case MessageHeader.MessageType.none: StayAlive(i); break; case MessageHeader.MessageType.newPlayer: break; case MessageHeader.MessageType.welcome: break; case MessageHeader.MessageType.setName: var message = new SetNameMessage(); message.DeserializeObject(ref reader); messagesQueue.Enqueue(message); PlayerData newPlayerData = GetPlayerData(connections[i]); newPlayerData.name = message.Name; NewPlayerJoined(connections[i]); break; case MessageHeader.MessageType.playerLeft: break; case MessageHeader.MessageType.moveRequest: var moveRequest = new MoverequestMessage(); moveRequest.DeserializeObject(ref reader); //messagesQueue.Enqueue(moveRequest); bool canmove = HandleMoveRequest(moveRequest, i); if (canmove) { NextPlayerTurn(); } break; case MessageHeader.MessageType.claimTreasureRequest: var treasureRquest = new ClaimTreasureRequestMessage(); treasureRquest.DeserializeObject(ref reader); HandleTreasureClaim(treasureRquest, i); break; case MessageHeader.MessageType.leaveDungeonRequest: var leaveDungeonRequest = new LeavesDungeonRequestMessage(); leaveDungeonRequest.DeserializeObject(ref reader); HandleLeaveDungeonRequest(leaveDungeonRequest, i); break; case MessageHeader.MessageType.defendRequest: var defendRequest = new DefendRequestMessage(); defendRequest.DeserializeObject(ref reader); HandleDefendRequest(defendRequest, i); break; case MessageHeader.MessageType.attackRequest: var attackRequest = new AttackRequestMessage(); attackRequest.DeserializeObject(ref reader); HandleAttackRequest(attackRequest, i); break; default: break; } } else if (cmd == NetworkEvent.Type.Disconnect) { PlayerLeftMessage playerLeftMessage = new PlayerLeftMessage { PlayerLeftID = i }; SendMessageToAll(playerLeftMessage); Debug.Log("Client disconnected"); connections[i] = default; } } } networkJobHandle = networkDriver.ScheduleUpdate(); ProcessMessagesQueue(); }
public void Tick() { if (!_serverDriver.IsCreated) { return; } _serverDriver.ScheduleUpdate().Complete(); // Accept all new connections while (true) { NetworkConnection connection = _serverDriver.Accept(); if (!connection.IsCreated) { break; } _connections.Add(connection); _lastPingTimes[connection] = Time; Debug.Log($"Client connected with internal Id {connection.InternalId}. Assigning actor number."); DataStreamWriter writer = _serverDriver.BeginSend(_reliablePipeline, connection); writer.WriteInt(Commands.AssignActorNumber); writer.WriteInt(connection.InternalId); _serverDriver.EndSend(writer); ClientConnected?.Invoke(connection.InternalId); } // process open connections for (var i = 0; i < _connections.Length; ++i) { // check for timeout NetworkConnection connection = _connections[i]; if (_clientConnectionTimeout > 0 && Time - _lastPingTimes[connection] > _clientConnectionTimeout) { connection.Disconnect(_serverDriver); Debug.LogWarning($"Disconnecting client {connection.InternalId} due to timeout"); ClientDisconnected?.Invoke(connection.InternalId); _connections.RemoveAtSwapBack(i); continue; } // pop events NetworkEvent.Type eventType; while ((eventType = _serverDriver.PopEventForConnection( connection, out DataStreamReader streamReader)) != NetworkEvent.Type.Empty) { if (eventType == NetworkEvent.Type.Data) { ReadDataEvent(connection, streamReader); } else if (eventType == NetworkEvent.Type.Disconnect) { Debug.Log($"Client {connection.InternalId} disconnected"); ClientDisconnected?.Invoke(connection.InternalId); _connections.RemoveAtSwapBack(i); if (i >= _connections.Length) { break; } } } } }
void Update() { // Update NetworkDriver Driver.ScheduleUpdate().Complete(); #region Update Connection List // Remove stale connections for (int i = 0; i < connections.Length; i++) { if (!connections[i].IsCreated) { connections.RemoveAtSwapBack(i); --i; } } // Accept new incoming connections NetworkConnection nc; while ((nc = Driver.Accept()) != default) { connections.Add(nc); Debug.Log("Accepted incoming connection"); } ServerConnectionsNumber.SetText("Open Connections: " + connections.Length); #endregion // Create a DataStreamReader and loop through all connections. DataStreamReader stream; for (int i = 0; i < connections.Length; i++) { // Skip a connection if it is stale. if (!connections[i].IsCreated) { continue; } // Pop event for current connection. Run while there is an event that needs to be processed. NetworkEvent.Type cmd; while ((cmd = Driver.PopEventForConnection(connections[i], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { #region uint data uint dataCode = stream.ReadByte(); try { switch (dataCode) { case (uint)DataCodes.PING: SendActionToClient(connections[i], (uint)DataCodes.PING); break; case (uint)DataCodes.DEBUG_MESSAGE: SendActionToClient(connections[i], (uint)DataCodes.DEBUG_MESSAGE); break; case (uint)DataCodes.P1_READY: pOneReady = true; PlayersReady(); break; case (uint)DataCodes.P2_READY: pTwoReady = true; PlayersReady(); break; case (uint)DataCodes.PASS_TURN: SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P1_STEEN: P1_ACTION = DataCodes.P1_STEEN; SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P1_PAPIER: P1_ACTION = DataCodes.P1_PAPIER; SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P1_SCHAAR: P1_ACTION = DataCodes.P1_SCHAAR; SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P2_STEEN: P2_ACTION = DataCodes.P2_STEEN; DetermineTurnWinner(); SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P2_PAPIER: P2_ACTION = DataCodes.P2_PAPIER; DetermineTurnWinner(); SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.P2_SCHAAR: P2_ACTION = DataCodes.P2_SCHAAR; DetermineTurnWinner(); SendActionToOther(connections[i], (uint)DataCodes.PASS_TURN); break; case (uint)DataCodes.END_GAME: EndGame(); break; default: break; } } catch (System.Exception e) { Debug.LogError(e.Message); } if (dataCode.ToString().StartsWith("3")) { int _data = int.Parse(dataCode.ToString().Split('3')[1]); if (Players.Count <= 0) { Players.Add(new DataStructs.User() { UserID = _data, PlayerNum = 1, Score = 0, Connection = connections[i] }); SendActionToClient(connections[i], (uint)DataCodes.ASSIGN_P1); } else { foreach (DataStructs.User user in Players) { // Check if the player has already logged in. if (user.UserID == _data) { SendActionToClient(connections[i], (uint)DataCodes.LOGIN_ERROR); duplicatePlayer = true; } } if (!duplicatePlayer) { Players.Add(new DataStructs.User() { UserID = _data, PlayerNum = 2, Score = 0, Connection = connections[i] }); SendActionToClient(connections[i], (uint)DataCodes.ASSIGN_P2); } } } #endregion } // On a disconnect event, reset connection to default values, making it a stale connection. else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("A user disconnected from the server."); connections[i] = default; } } } }