private void EndSend(IAsyncResult ar) { try { if (!(this.udpClient is null)) { UdpDatagramEventArgs e = (UdpDatagramEventArgs)ar.AsyncState; this.udpClient.EndSend(ar); lock (this.writeQueue) { if (!(this.writeQueue.First is null)) { KeyValuePair <IPEndPoint, byte[]> Rec = this.writeQueue.First.Value; this.writeQueue.RemoveFirst(); this.udpClient.BeginSend(Rec.Value, Rec.Value.Length, Rec.Key, this.EndSend, new UdpDatagramEventArgs(Rec.Key, Rec.Value)); } else { this.isWriting = false; } }
internal void UdpDatagramReceived(PeerToPeerNetwork Sender, UdpDatagramEventArgs e) { LinkedList<KeyValuePair<ushort, byte[]>> LostPackets = null; byte[] FirstPacket = null; ushort FirstPacketNr = 0; ushort PacketNr; byte[] Packet; byte[] Data = e.Data; int Len = Data.Length; int Pos = 0; int PacketLen; int Offset; byte b; lock (this.udpReceiveLock) { while (Pos < Len) { b = Data[Pos++]; PacketLen = (b & 127); Offset = 7; while (Pos < Len && (b & 128) != 0) { b = Data[Pos++]; PacketLen |= (b & 127) << Offset; Offset += 7; } if (Pos + 2 > Len) break; PacketNr = Data[Pos++]; PacketNr |= (ushort)(Data[Pos++] << 8); if (Pos + PacketLen > Len) break; Packet = new byte[PacketLen]; Array.Copy(Data, Pos, Packet, 0, PacketLen); Pos += PacketLen; if ((short)(PacketNr - this.lastReceivedPacket) > 0) { if (FirstPacket == null) { FirstPacket = Packet; FirstPacketNr = PacketNr; } else { if (LostPackets == null) LostPackets = new LinkedList<KeyValuePair<ushort, byte[]>>(); LostPackets.AddFirst(new KeyValuePair<ushort, byte[]>(PacketNr, Packet)); // Reverse order } } } if (FirstPacket != null) this.lastReceivedPacket = FirstPacketNr; } BinaryEventHandler h = this.OnReceived; if (h != null) { if (LostPackets != null) { foreach (KeyValuePair<ushort, byte[]> P in LostPackets) { try { h(this, P.Value); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace.ToString()); } } } if (FirstPacket != null) { try { h(this, FirstPacket); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace.ToString()); } } } }
private void p2pNetwork_OnUdpDatagramReceived(PeerToPeerNetwork Sender, UdpDatagramEventArgs e) { Player Player; lock (this.remotePlayersByEndpoint) { if (!this.remotePlayersByEndpoint.TryGetValue(e.RemoteEndpoint, out Player)) return; } if (Player.Connection != null) Player.Connection.UdpDatagramReceived(Sender, e); }