private void ProcessIncomingPackets() { while (udpNetwork.TryRead(receiveBuffer, 0, out var length)) { packetReader.BaseStream.Position = 0; //TODO: add read limit LastDataReceiveTime = Time.unscaledTime; try { var packetType = (PacketType)packetReader.ReadByte(); switch (packetType) { case PacketType.JoinToMatch: if (localPlayerId != 0) { continue; } localPlayerId = packetReader.ReadUInt32(); ServerIsFull = localPlayerId == 0; SendSyncPacket(); break; case PacketType.Sync: ParseIncomingSyncPacket(); break; } } catch (Exception e) { Debug.LogError("Incoming packet processing error! Details: " + e); } } }
private void ProcessIncomingPackets() { while (udpNetwork.TryRead(receiveBuffer, 0, out var length)) { packetReader.BaseStream.Position = 0; //TODO: add read limit try { var packetType = (PacketType)packetReader.ReadByte(); Client existsClient; switch (packetType) { case PacketType.JoinToMatch: packetWriter.BaseStream.Position = 0; packetWriter.Write((byte)PacketType.JoinToMatch); packetWriter.Write(0u); var isClientExists = false; foreach (var client in clients) { if (client.IsLocal) { continue; } if (client.remoteIpEndPoint.Equals(udpNetwork.lastReadRemoteIpEndPoint)) { packetWriter.BaseStream.Position -= sizeof(uint); packetWriter.Write(client.id); isClientExists = true; break; } } if (clients.Count < Game.Config.MaxPlayers && !isClientExists) { var client = new Client(++playerIdSequence, new IPEndPoint(new IPAddress(udpNetwork.lastReadRemoteIpEndPoint.Address.GetAddressBytes()), udpNetwork.lastReadRemoteIpEndPoint.Port)); clients.Add(client); packetWriter.BaseStream.Position -= sizeof(uint); packetWriter.Write(client.id); futureCommands.Add(new PlayerCommand { playerId = 0, command = new Commands.AddPlayer { id = client.id } }); } udpNetwork.SendToLastClient(sendBuffer, 0, (int)packetWriter.BaseStream.Position); break; case PacketType.Sync: existsClient = ReadIncomingPacketSyncBodyAndGetValidClient(); if (existsClient == null) { continue; } SendCommandsToClient(existsClient); break; case PacketType.PlayerCommand: existsClient = ReadIncomingPacketSyncBodyAndGetValidClient(); if (existsClient == null) { continue; } SendCommandsToClient(existsClient); ParseIncomingPlayerCommand(existsClient); break; } } catch (Exception e) { Debug.LogError("Incoming packet processing error! Details: " + e); } } }