private void Run() { try { this.ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this.ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); this.ListenSocket.Bind(this.LocalEndPoint); var buffer = new byte[16384]; EndPoint remoteEP; int inCount; while (!this.IsCanceled) { try { remoteEP = new IPEndPoint(IPAddress.Any, 0); inCount = this.ListenSocket.ReceiveFrom(buffer, ref remoteEP); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.Interrupted) { return; } else { throw; } } if (TinyPacketReceived != null) { var newBuffer = new byte[inCount]; Buffer.BlockCopy(buffer, 0, newBuffer, 0, inCount); Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "TinyMessage [{0} <- {1}]", TinyPacket.ParseHeaderOnly(newBuffer, 0, inCount), remoteEP)); var invokeArgs = new object[] { this, new TinyPacketEventArgs(newBuffer, 0, inCount, remoteEP as IPEndPoint) }; foreach (Delegate iDelegate in TinyPacketReceived.GetInvocationList()) { ISynchronizeInvoke syncer = iDelegate.Target as ISynchronizeInvoke; if (syncer == null) { iDelegate.DynamicInvoke(invokeArgs); } else { syncer.BeginInvoke(iDelegate, invokeArgs); } } } } } catch (ThreadAbortException) { } finally { if (this.ListenSocket != null) { ((IDisposable)this.ListenSocket).Dispose(); this.ListenSocket = null; } } }
public TinyPacket GetPacketWithoutData() { return(TinyPacket.ParseHeaderOnly(this.Buffer, this.Offset, this.Count)); }