private void SendServerHandshake(int targetClientIndex, ushort setClientID) { ServerHandshakeMsg msg; Debug.Log("[Notice] Sending player list and assigned ID to newly connected player... "); //Create handshake object and assign client its ID msg = new ServerHandshakeMsg(setClientID); //Setting up list of player data (if any) to send to newly connected player foreach (KeyValuePair <int, NetworkObjects.NetworkPlayer> client in m_clientIDDict) { msg.players.Add(client.Value); } //Send handshake to client SendToClient(JsonUtility.ToJson(msg), m_Connections[targetClientIndex]); if (m_clientIDDict.ContainsKey(m_Connections[targetClientIndex].InternalId)) { Debug.Log("[Notice] Handshake sent to Client! " + m_Connections[targetClientIndex].InternalId + " (InternalId) " + m_clientIDDict[m_Connections[targetClientIndex].InternalId].clientID + " (clientID)"); } else { Debug.LogWarning("[Warning] Handshake sent to Client, but given InternalId is not a key in m_clientIDDict."); } ShowClientList(); }
private void OnData(DataStreamReader stream) { NativeArray <byte> bytes = new NativeArray <byte>(stream.Length, Allocator.Temp); stream.ReadBytes(bytes); string recMsg = Encoding.ASCII.GetString(bytes.ToArray()); NetworkHeader header = JsonUtility.FromJson <NetworkHeader>(recMsg); switch (header.cmd) { case Commands.HANDSHAKE: HandshakeMsg hsMsg = JsonUtility.FromJson <HandshakeMsg>(recMsg); Debug.Log("[Notice] Handshake message received!"); break; case Commands.PLAYER_UPDATE: //shouldnt happen Debug.LogError("[Error] Player update message received! Client shouldn't receive messages from clients."); break; case Commands.SERVER_UPDATE: ServerUpdateMsg suMsg = JsonUtility.FromJson <ServerUpdateMsg>(recMsg); //Debug.Log("[Routine] Server update message received!"); UpdateRemotePlayers(suMsg.players); break; case Commands.PONG: if (bVerboseDebug) { //Debug.Log("[Routine] Pong message received!"); } break; case Commands.SERVER_HANDSHAKE: ServerHandshakeMsg shMsg = JsonUtility.FromJson <ServerHandshakeMsg>(recMsg); Debug.Log("[Notice] Handshake from server received!"); m_clientIDDict.Add(shMsg.clientID, localClientCharacterRef); //Add local character to player dictionary m_thisClientID = shMsg.clientID; //keep a reference to local player ID SpawnRemotePlayers(shMsg.players); //Spawn remote players StartCoroutine(UploadClientDataRoutine(m_clientUpdateInterval)); //Start routinely updating server with local cube character data break; case Commands.NEW_PLAYER: PlayerUpdateMsg puMSg = JsonUtility.FromJson <PlayerUpdateMsg>(recMsg); Debug.Log("[Notice] A new player has connected. (" + puMSg.player.clientID + ")"); SpawnRemotePlayer(puMSg.player); break; case Commands.PLAYER_DISCONNECT: PlayerIDMsg pdMSg = JsonUtility.FromJson <PlayerIDMsg>(recMsg); Debug.Log("[Notice] A player has disconnected. (" + pdMSg.clientID + ")"); RemoveRemotePlayer(pdMSg.clientID); break; default: Debug.LogError("[Error] Unrecognized message received!"); break; } }