// MonoBehaviour /////////////////////////////////////////////////////// void UpdateServer() { while (serverSocket != null && serverSocket.Poll(0, SelectMode.SelectRead)) { int msgLength = serverSocket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref serverNewClientEP); //Debug.Log($"KCP: server raw recv {msgLength} bytes = {BitConverter.ToString(buffer, 0, msgLength)}"); // calculate connectionId from endpoint int connectionId = serverNewClientEP.GetHashCode(); // is this a new connection? if (!connections.TryGetValue(connectionId, out KcpServerConnection connection)) { // add it to a queue connection = new KcpServerConnection(serverSocket, serverNewClientEP); //acceptedConnections.Writer.TryWrite(connection); connections.Add(connectionId, connection); Debug.LogWarning($"KCP: server added connection {serverNewClientEP}"); // setup connected event connection.OnConnected += () => { // call mirror event Debug.LogWarning($"KCP OnServerConnected({connectionId})"); }; // setup data event connection.OnData += (message) => { // call mirror event Debug.LogWarning($"KCP OnServerDataReceived({connectionId}, {BitConverter.ToString(message.Array, message.Offset, message.Count)})"); }; // setup disconnected event connection.OnDisconnected += () => { // remove from connections connections.Remove(connectionId); // call mirror event Debug.LogWarning($"KCP OnServerDisconnected({connectionId})"); }; // send handshake connection.Handshake(); } connection.RawInput(buffer, msgLength); } // tick all server connections foreach (KcpServerConnection connection in connections.Values) { connection.Tick(); connection.Receive(); } }
private async UniTaskVoid ServerHandshake(EndPoint endpoint, byte[] data, int msgLength) { var connection = new KcpServerConnection(socket, endpoint, delayMode, SendWindowSize, ReceiveWindowSize); connectedClients.Add(endpoint as IPEndPoint, connection); connection.Disconnected += () => { connectedClients.Remove(endpoint as IPEndPoint); }; connection.DataSent += (length) => { sentBytes += length; }; connection.RawInput(data, msgLength); await connection.HandshakeAsync(); // once handshake is completed, then the connection has been accepted Connected.Invoke(connection); }