async void ReceiveAsync(UdpClient client, CancellationToken token) { while (!token.IsCancellationRequested) { try { var result = await client.ReceiveAsync().ConfigureAwait(false); var receiveString = Encoding.ASCII.GetString(result.Buffer); var match = RegexMatcher.Match(receiveString); if (!match.Success) { return; } int portcheck = Convert.ToInt32(match.Groups["port"].Value); if (portcheck <= 0 || portcheck > 65535) { return; } var infoHash = InfoHash.FromHex(match.Groups["hash"].Value); var uri = new Uri("ipv4://" + result.RemoteEndPoint.Address + ':' + portcheck); PeerFound?.Invoke(this, new LocalPeerFoundEventArgs(infoHash, uri)); } catch { } } }
async void ReceiveAsync(UdpClient client, CancellationToken token) { while (!token.IsCancellationRequested) { try { UdpReceiveResult result = await client.ReceiveAsync().ConfigureAwait(false); string[] receiveString = Encoding.ASCII.GetString(result.Buffer) .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); string portString = receiveString.FirstOrDefault(t => t.StartsWith("Port: ", StringComparison.Ordinal)); string hashString = receiveString.FirstOrDefault(t => t.StartsWith("Infohash: ", StringComparison.Ordinal)); string cookieString = receiveString.FirstOrDefault(t => t.StartsWith("cookie", StringComparison.Ordinal)); // An invalid response was received if these are missing. if (portString == null || hashString == null) { continue; } // If we received our own cookie we can ignore the message. if (cookieString != null && cookieString.Contains(Cookie)) { continue; } // If the port is invalid, ignore it! int portcheck = int.Parse(portString.Split(' ').Last()); if (portcheck <= 0 || portcheck > 65535) { continue; } var infoHash = InfoHash.FromHex(hashString.Split(' ').Last()); var uri = new Uri($"ipv4://{result.RemoteEndPoint.Address}{':'}{portcheck}"); PeerFound?.InvokeAsync(this, new LocalPeerFoundEventArgs(infoHash, uri)); } catch (FileNotFoundException) { throw; } catch { } } }
public void RaisePeerFound(InfoHash infoHash, Uri uri) => PeerFound?.Invoke(this, new LocalPeerFoundEventArgs(infoHash, uri));