// Packet event handler private void RecieveConnection(RecievedPacket packet) { if (peerManager != null) { // Get the request to connect if (packet.type == PacketType.connectToNetwork && packet.value == PacketValue.addUpdate) { if (InLobby) { // Get the connecting peer and assign it a new Id peerManager.RecievePeer(peerManager.GetPeerDataFromBytes(packet.data), packet.GetTimeDifference()); SendCurrentNetwork(); } } // Get the change in the network else if (packet.type == PacketType.returnNetwork && packet.value == PacketValue.completeList) { peerManager.RetrievePeersFromBytes(packet); if (!InLobby) { JoinLobby(false); } UpdateLobbyMenu(); } // Get the request to disconnect else if (packet.type == PacketType.disconnectNetwork && packet.value != PacketValue.confirmation) { InvokeDisconnect(packet.data[0]); } } }
// Remove a packet when it the timer ran out public void RemoveRecievedPacket(RecievedPacket status) { if (!RecievedPacketLocked) { RecievedPackets.Remove(status); } }
public static void ParseData(List <byte> rawPacket, string ip, ushort port) { List <byte> data = rawPacket.GetRange(Packet.Reserved, rawPacket.Count - Packet.Reserved); PacketType type = (PacketType)rawPacket[0]; PacketValue value = (PacketValue)rawPacket[1]; byte id = rawPacket[2]; bool reliable = BitConverter.ToBoolean(rawPacket.ToArray(), 3); ushort packetId = BitConverter.ToUInt16(rawPacket.ToArray(), 4); long timeSend = BitConverter.ToInt64(rawPacket.ToArray(), 6); RecievedPacket recievedPacket = new RecievedPacket(data, id, type, value, ip, port, timeSend, packetId); // Check up if the packet was already recieved if (!CheckIfPacketWasAlreadyRecieved(id, packetId)) { // Queue the packet for processing RecievedPackets.Add(recievedPacket); QueuedPackets.Enqueue(recievedPacket); } // Send a confirmation back to the user if (reliable) { MultiplayerManager.sender.QueuePacket( new Packet(rawPacket.GetRange(4, 2), MultiplayerManager.LocalId, type, PacketValue.confirmation, ip, port) ); } }
// Convert bytes to the list and callback what to do with the object info public void GetListFromBytes(RecievedPacket packet, Action <List <object>, float> callback) { int curI = 0; while (curI < packet.data.Count) { byte length = packet.data[curI]; curI++; callback.Invoke(DataConverter.ConvertByteToObject <T>(packet.data.GetRange(curI, length)), packet.GetTimeDifference()); curI += length; } }
// Recieve confirmation packets private void RecievePacket(RecievedPacket packet) { if (packet.value == PacketValue.confirmation) { ushort id = BitConverter.ToUInt16(packet.data.ToArray(), 0); foreach (PacketStatus status in waitingForConfirmation) { if (status.packetId == id) { status.succes?.Invoke(status); Debug.Log("Packet confirmed: " + id); RemoveWaitingPacket(status); return; } } Debug.LogError("No packet found to confirm: " + id); } }
public void RetrievePeersFromBytes(RecievedPacket packet) { peerList.GetListFromBytes(packet, RecievePeer); }