IEnumerator StartServer() { _server = new TcpListener(IPAddress.Any, 7777); _server.Start(); bool connected = false; Thread connectThread = new Thread(() => { _connectedClient = _server.AcceptTcpClient(); _networkStream = _connectedClient.GetStream(); connected = true; }); connectThread.Start(); while (connected == false) { yield return(null); } Debug.Log("connected!"); _networkListening = true; ReadClientMessagesAsync(); NetworkMessage message = new NetworkMessage(); message.type = NetworkMessage.Type.Chat; message.chat.message = "hello!"; SendNetworkMessage(message); message.type = NetworkMessage.Type.InitializeClient; message.initializeClient.playerID = 2; _playerID = 1; SendNetworkMessage(message); message.type = NetworkMessage.Type.DiskSpawn; for (int i = 0; i < _diskJsons.Length; i++) { int player = (i % 2) + 1; DiskJson disk = _diskJsons[i]; SpawnDisk(disk.name, player); message.diskSpawn.player = player; message.diskSpawn.diskName = disk.name; SendNetworkMessage(message); } _currentPlayer = 1; _currentPlayerDisplay.text = _currentPlayer == _playerID ? "It's your turn!" : $"Player {_currentPlayer}'s turn"; if (_currentPlayer == _playerID) { _diskGhost.SetActive(true); } message.type = NetworkMessage.Type.PlayerTurnUpdateMessage; message.playerTurnUpdate.currentPlayer = _currentPlayer; SendNetworkMessage(message); _endTurnButton.onClick.AddListener(EndTurnServer); }
async void ReadServerMessagesAsync() { StreamReader reader = new StreamReader(_networkStream); while (_networkListening) { Task <string> readTask = reader.ReadLineAsync(); await readTask; string json = readTask.Result; if (string.IsNullOrWhiteSpace(json)) { continue; } Debug.Log(json); NetworkMessage message = JsonUtility.FromJson <NetworkMessage>(json); switch (message.type) { case NetworkMessage.Type.Chat: Debug.Log(message.chat.message); break; case NetworkMessage.Type.DiskSpawn: SpawnDisk(message.diskSpawn.diskName, message.diskSpawn.player); break; case NetworkMessage.Type.DiskMove: Disk disk = _disks[message.diskMove.diskID]; disk.Position = message.diskMove.targetLocation; disk.RemainingMoves = message.diskMove.remainingMoves; GameObject actor = _actorByID[disk.ID]; FlapAnimation flapAnimation = new FlapAnimation { Actor = actor, TargetLocation = disk.Position }; _flapQueue.Enqueue(flapAnimation); break; case NetworkMessage.Type.InitializeClient: _playerID = message.initializeClient.playerID; break; case NetworkMessage.Type.PlayerTurnUpdateMessage: _currentPlayer = message.playerTurnUpdate.currentPlayer; _currentPlayerDisplay.text = _currentPlayer == _playerID ? "It's your turn!" : $"Player {_currentPlayer}'s turn"; if (_currentPlayer == _playerID) { _diskGhost.SetActive(true); } break; default: Debug.LogError($"{message.type} is not a valid value for {typeof(NetworkMessage.Type)}."); break; } } }