async void ReceiveAsync(UdpClient client, CancellationToken token) { Task sendTask = null; while (!token.IsCancellationRequested) { try { UdpReceiveResult result = await client.ReceiveAsync(); byte[] data = result.Buffer; if (data.Length < 16) { return; //bad request } var request = UdpTrackerMessage.DecodeMessage(data.AsSpan(0, data.Length), MessageType.Request); if (sendTask != null) { try { await sendTask; } catch { } } sendTask = request.Action switch { 0 => ReceiveConnect(client, (ConnectMessage)request, result.RemoteEndPoint), 1 => ReceiveAnnounce(client, (AnnounceMessage)request, result.RemoteEndPoint), 2 => ReceiveScrape(client, (ScrapeMessage)request, result.RemoteEndPoint), 3 => ReceiveError(client, (ErrorMessage)request, result.RemoteEndPoint), _ => throw new InvalidOperationException($"Invalid udp message received: {request.Action}") }; } catch (Exception e) { logger.Exception(e, "Exception while receiving a message"); } } }
private static bool IsBrowserAlive(string browserHostname) { const int DefaultBrowserPort = 1434; const int sendTimeout = 1000; const int receiveTimeout = 1000; const byte ClntUcastEx = 0x03; byte[] requestPacket = new byte[] { ClntUcastEx }; byte[] responsePacket = null; using (UdpClient client = new UdpClient(AddressFamily.InterNetwork)) { try { Task <int> sendTask = client.SendAsync(requestPacket, requestPacket.Length, browserHostname, DefaultBrowserPort); Task <UdpReceiveResult> receiveTask = null; if (sendTask.Wait(sendTimeout) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeout)) { responsePacket = receiveTask.Result.Buffer; } } catch { } } return(responsePacket != null && responsePacket.Length > 0); }
async Task <bool> QueryCurrentTime(string rpHostname) { try { using (var rClient = new UdpClient(rpHostname, 123)) { var rData = new byte[48]; rData[0] = 0x1B; await rClient.SendAsync(rData, rData.Length); var rResult = await Task.WhenAny(rClient.ReceiveAsync(), Task.Delay(5000)) as Task <UdpReceiveResult>; if (rResult == null) { return(false); } rData = (await rResult).Buffer; var rIntegerPart = (ulong)rData[40] << 24 | (ulong)rData[41] << 16 | (ulong)rData[42] << 8 | rData[43]; var rFractionPart = (ulong)rData[44] << 24 | (ulong)rData[45] << 16 | (ulong)rData[46] << 8 | rData[47]; var rMilliseconds = rIntegerPart * 1000 + (rFractionPart >> 20); r_Time = new DateTimeOffset(1900, 1, 1, 0, 0, 0, TimeSpan.Zero).AddMilliseconds(rMilliseconds).ToOffset(TimeSpan.FromHours(9.0)); r_InitialTick = Stopwatch.GetTimestamp(); return(true); } } catch { return(false); } }
private async void DoWork() { try { var beaconPort = ConfigurationManager.AppSettings["UdpBeaconPort"]; Logger.Info($"{nameof(UdpBeaconReceiverJob)} is listening to [{beaconPort}]."); if (!int.TryParse(beaconPort, out var parsedBeaconPort)) { Logger.Error($"{beaconPort} is not a valid value for BeaconPort"); return; } using (var broadcaster = new UdpClient()) { var ep = new IPEndPoint(IPAddress.Any, parsedBeaconPort); broadcaster.ExclusiveAddressUse = false; broadcaster.AllowNatTraversal(true); broadcaster.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); broadcaster.Client.Bind(ep); Logger.Info($"Binding ({nameof(UdpBeaconReceiverJob)}) on [{ep}]"); while (!_cancellation.IsCancellationRequested) { var receive = await broadcaster.ReceiveAsync(); Logger.Debug($"<--- [{receive.RemoteEndPoint.Prettify()}] {Encoding.UTF8.GetString(receive.Buffer)}"); } } Logger.Info("Beacon receiver terminating."); } catch (Exception e) { Logger.Error(e); } }
public Sender(IPEndPoint endPoint) { udpSender = new UdpClient(); udpSender.Connect(endPoint); var data = Encoding.UTF8.GetBytes("hello"); Send(data); var b = udpSender.ReceiveAsync(); b.Wait(); udpSender.Dispose(); var port = int.Parse(Encoding.UTF8.GetString(b.Result.Buffer)); var newEP = new IPEndPoint(endPoint.Address, port); udpSender = new UdpClient(); udpSender.Connect(newEP); Send(data); ThreadPool.QueueUserWorkItem(ListenerThread, endPoint); }
private async void UpdateData(IPEndPoint endPoint) { var telemetryListener = new UdpClient(); try { InitializeUDPListener(telemetryListener, endPoint); while (isListening) { UdpReceiveResult result = await telemetryListener.ReceiveAsync(); if (result.Buffer.Length < TelemetryDataLength) { continue; } result.Buffer.AsSpan(0..TelemetryDataLength).CopyTo(telemetryData); } } catch (SocketException ex) { if (ex.ErrorCode != (int)SocketError.TimedOut) { MessageBox.Show( ex.Message, caption: "UDP error", MessageBoxButton.OK, MessageBoxImage.Error); } } finally { telemetryListener.Client.Shutdown(SocketShutdown.Both); telemetryListener.Client.Close(); } }
public void Start() { Task.Run(async() => { using (UdpClient udpClient = new UdpClient(Constants.Network.PORT)) { //IPEndPoint localEp = new IPEndPoint(GetLocalIps().First(), Constants.Network.PORT); //udpClient.Client.Bind(localEp); IPAddress multicastAddr = IPAddress.Parse(Host); udpClient.JoinMulticastGroup(multicastAddr); while (true)//TODO: can stop { var data = await udpClient.ReceiveAsync(); AudioPacket audioPacket = Serializer.Deserialize <AudioPacket>(new MemoryStream(data.Buffer)); DateTime sampleStartTime = new DateTime(audioPacket.StartTicks); long targetSample = (long)((sampleStartTime - zeroPositionTime - LocalJitter + Delay - TimeSpan.FromMilliseconds(LocalClockOffset)).TotalSeconds * Constants.Audio.SAMPLE_RATE); long targetPosition = targetSample * Constants.Audio.BIT_DEPTH / 8 * Constants.Audio.CHANNELS; WavePlayer.AddAudioData(targetPosition, audioPacket.AudioData); } } }); }
public async Task Listen(int port, int tickrate) { this.udp = new UdpClient(port); new Timer(Tick, null, 0, 1000 / tickrate); while (true) { var res = await udp.ReceiveAsync(); var br = new BinaryReader(new MemoryStream(res.Buffer)); var header = (Header)br.ReadByte(); switch (header) { case Header.commandJoin: AddPlayer(NetEntity <Join> .Decode(br), res.RemoteEndPoint); break; case Header.input: MovePlayer(NetEntity <Input> .Decode(br), res.RemoteEndPoint); break; default: throw new Exception($"Unsupported header: {header}"); } } }
public void Start() { Task.Run(async() => { try { while (true) { var msg = await udpClient.ReceiveAsync(); if (msg != null && msg.Buffer != null) { var text = Encoding.UTF8.GetString(msg.Buffer); OnMessageReceived(text); } } } catch (ObjectDisposedException) { } catch (Exception ex) { TestLogger.Log($"Error in UDP listener: {ex.ToString()}"); } }); }
static async Task Main(string[] args) { var udpClient = new UdpClient(8000); IPEndPoint endpoint = null; //var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); try { //udpClient.Connect(IPAddress.Parse("127.0.0.1"), 8000); while (true) { var data = await udpClient.ReceiveAsync(); if (data.Buffer.Length > 0) { Console.WriteLine(Encoding.UTF8.GetString(data.Buffer)); } } } catch (Exception exception) { Console.WriteLine(exception.Message); } }
//private void PrepareUdpClient() //{ // client = new UdpClient(8001); //} private async void OnReady(object sender, RoutedEventArgs e) { var recieverUdpClient = new UdpClient(8001); try { recieverUdpClient.JoinMulticastGroup(IPAddress.Parse("225.1.10.8"), 10); } catch (Exception exception) { MessageBox.Show(exception.Message); } while (true) { var result = await recieverUdpClient.ReceiveAsync(); messages.Add(Encoding.UTF8.GetString(result.Buffer)); } //var message = Encoding.UTF8.GetString(result.Buffer); //messages.Add(message); }
private async Task <DnsPacket> ResolveQuery(byte[] packet) { Logger.Info("Handling query"); using (var udpClient = new UdpClient()) { var sendTask = udpClient.SendAsync(packet, packet.Length, remoteEndPoint); var sendRes = await Task.WhenAny(sendTask, Task.Delay(1500)); if (sendRes == sendTask) { await sendTask; } Logger.Info("sent to server"); var receiveTask = udpClient.ReceiveAsync(); var res = await Task.WhenAny(receiveTask, Task.Delay(1500)); UdpReceiveResult result; if (res == receiveTask) { result = await receiveTask; } else { throw new TimeoutException("Query timed out"); } Logger.Info("received from server"); if (!Equals(result.RemoteEndPoint, remoteEndPoint)) { throw new ArgumentException(); } var parsedAnswer = DnsPacketParser.ParsePacket(result.Buffer); Logger.Info("Received answer for <{0} {1} {2}>", parsedAnswer.Queries[0].Name, parsedAnswer.Queries[0].AnswerType, parsedAnswer.Queries[0].Class); return(parsedAnswer); } }
private async void RecievePackets() { while (true) { try { var result = await _udpClient.ReceiveAsync(); byte[] responseBytes = result.Buffer; if (responseBytes == null) { continue; } var response = new AniDBResponse(responseBytes, _encoding); new Task(() => HandleResponse(response)).Start(); } catch (ObjectDisposedException ode) { break; } } }
public async void AwaitDiscoveryReply() { try { using (var client = new UdpClient(4568, AddressFamily.InterNetwork)) { while (true) { Debug.WriteLine("Awaiting DR"); var result = await client.ReceiveAsync(); Debug.WriteLine("Received DR"); var stateProtocol = StateProtocol.FromBytes(result.Buffer); if (stateProtocol.ProtocolType == ProtocolRequest.DeviceDiscoveryReply) { var robeatsDevice = new RobeatsDevice { Id = stateProtocol.DeviceId, Name = stateProtocol.DeviceName, /*EndPoint = client.Client.RemoteEndPoint,*/ StateProtocol = stateProtocol }; OnDiscoveryReply(new DeviceDiscoveryEventArgs { RobeatsDevice = robeatsDevice }); } } } } catch (Exception ex) { Debug.WriteLine(ex); } }
private async Task SendClientHandshake() { if (_udpClient != null) { _isRunning = true; await Task.Run(async() => { while (!IsConnected && IsRunning) { _udpClient.Connect(_address, _port); var password = Encoding.ASCII.GetBytes(SettingsHandler.HandShakeChannel); Log.Debug(DateTime.Now + " Sending udp connection handshake"); _udpClient.Send(password, password.Length); var receivedResults = await _udpClient.ReceiveAsync(); var returnData = Encoding.ASCII.GetString(receivedResults.Buffer); Log.Debug(DateTime.Now + " udp connection handshake returnData: " + returnData); if (returnData.Contains(SettingsHandler.TCodeVersion)) { UpdateConnected(true); } } }); } }
public void Init() { try { Inited = false; IPEndPoint groupep = new IPEndPoint( Config.UdpHost.Equals("any", StringComparison.OrdinalIgnoreCase) ? IPAddress.Any : IPAddress.Parse(Config.UdpHost), Config.UdpPort); udpListener = new UdpClient(groupep); Log.Information("Udp Server is initialized and listening on: {0}:{1}", Config.UdpHost, Config.UdpPort); Inited = true; } catch (SocketException se) { Log.Error(se, "Error when initialize the Udp Listener"); } if (Inited == true) { Task.Factory.StartNew(async() => { Running = true; while (Running) { var result = await udpListener.ReceiveAsync(); if (result != null) { await handler.Receive(result.RemoteEndPoint, result.Buffer); } } }); } }
public static async void Accept() { try { UdpReceiveResult receiveResult = await UdpClient.ReceiveAsync(); string received = Encoding.ASCII.GetString(receiveResult.Buffer, 0, receiveResult.Buffer.Length); JsonSerializer serializer = new JsonSerializer(); using (StringReader sr = new StringReader(received)) using (JsonReader reader = new JsonTextReader(sr)) { RequestMessage requestMessage = serializer.Deserialize <RequestMessage>(reader); requestMessage.RunMethod(); //ResponseMessage responseMessage = new ResponseMessage //{ // Id = requestMessage.Id, // Result = MessageResult.OK //}; //using (StreamWriter sw = new StreamWriter(stream)) //using (JsonWriter writer = new JsonTextWriter(sw)) //{ // serializer.Serialize(writer, responseMessage); //} } //client.Close(); Accept(); } catch (System.Net.Sockets.SocketException ex) { Debug.WriteLine(ex.Message); } }
private void Receiver() { var client = new UdpClient(Port, AddressFamily.InterNetwork); //label3.Text = string.Format("Status: Receiving..."); try { var dataReceived = client.ReceiveAsync(); var message = GetString(dataReceived.Result.Buffer); var s_ip = dataReceived.Result.RemoteEndPoint.Address.ToString(); var s_port = dataReceived.Result.RemoteEndPoint.Port; var ack = CommandHandler.GetCommand(new Command[] { new Ack() }, message); if (ack is Ack) { MessageBox.Show(string.Format("Received ACK from {0}:{1}", s_ip, s_port)); //label3.Text = string.Format("Status: Received ACK from {0}:{1}", s_ip, s_port); } } catch (Exception ex) { //MessageBox.Show("Exception: " + ex.Message); } client.Close(); client.Dispose(); }
private async Task ReceiveFromAsync(UdpClient client) { while (IsRunning) { try { var result = await client.ReceiveAsync(); var message = MessageParser.Decode(result.Buffer); _logger.Trace($"Got\n{message}"); if (message.Type == MessageType.Response && message.AuthoriativeAnswer && message.ResponseCode == ResponseCode.NoError) { Handle(message); } } catch (Exception e) { Console.WriteLine(e); } } }
private void ReceivedLoop(UdpClient udp, CancellationToken cancellationToken) { while (true) { bool isRecieved = false; udp.ReceiveAsync().WithCancellation(cancellationToken).ContinueWith(x => { if (x != null && x.Status != TaskStatus.Faulted) { if (x.Result != null && x.Result.Buffer != null && x.Result.Buffer.Length > 0) { Received?.Invoke(this, x.Result.Buffer); } } isRecieved = true; }); while (isRecieved == false) { Thread.Sleep(THREAD_DELAY_MS); } } }
async void Listen() { while (appRunning) { try { UdpReceiveResult udpReceiveResult = await udpClientListener.ReceiveAsync(); string receivedData = Encoding.ASCII.GetString(udpReceiveResult.Buffer); Console.WriteLine(); Console.WriteLine($"Data received: {receivedData}"); Console.Write("Send over port 12345>"); } catch (ObjectDisposedException ex) { Console.WriteLine(ex.ToString()); } catch (SocketException ex) { Console.WriteLine(ex.ToString()); } } }
public async Task Start() { while (true) { try { var result = await _server.ReceiveAsync(); if (result.Buffer.Length > 1) { if (!_clients.Contains(result.RemoteEndPoint)) { _clients.Add(result.RemoteEndPoint); } foreach (var v in _clients) { _server.Send(result.Buffer, result.Buffer.Length, v); } } } catch { } } }
private async Task ListenAsync() { // Start packet handler. await StartAsync(); // Listen. while (State != ConnectionState.NotConnected) { UdpReceiveResult data; try { data = await _socket.ReceiveAsync(); } catch (SocketException e) { await DisconnectInternal(HazelInternalErrors.SocketExceptionReceive, "Socket exception while reading data: " + e.Message); return; } catch (Exception) { return; } if (data.Buffer.Length == 0) { await DisconnectInternal(HazelInternalErrors.ReceivedZeroBytes, "Received 0 bytes"); return; } // Write to client. await Pipeline.Writer.WriteAsync(data.Buffer); } }
async void ReceiveAsync(UdpClient client, CancellationToken token) { while (!token.IsCancellationRequested) { try { UdpReceiveResult result = await client.ReceiveAsync().ConfigureAwait(false); if (!token.IsCancellationRequested) { MessageReceived?.Invoke(result.Buffer, result.RemoteEndPoint); } } catch (SocketException ex) { // If the destination computer closes the connection // we get error code 10054. We need to keep receiving on // the socket until we clear all the error states if (ex.ErrorCode == 10054) { continue; } } catch { // Do nothing. } } }
static async Task FillPipeAsync(UdpClient client, PipeWriter writer) { // size of a single CarUpdateDatagram const int minBufferSize = 328; while (true) { var memory = writer.GetMemory(minBufferSize); var udpResult = await client.ReceiveAsync(); udpResult.Buffer.CopyTo(memory); writer.Advance(udpResult.Buffer.Length); var result = writer.FlushAsync(); if (result.IsCompleted && false) { break; } } await writer.CompleteAsync(); }
async Task RunUdpListener() { IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT); udpClient = new UdpClient(endPoint); Console.WriteLine($"LoRaWAN server started on port {PORT}"); while (true) { UdpReceiveResult receivedResults = await udpClient.ReceiveAsync(); //Console.WriteLine($"UDP message received ({receivedResults.Buffer.Length} bytes) from port: {receivedResults.RemoteEndPoint.Port}"); //Todo check that is an ack only, we could do a better check in a future verstion if (receivedResults.Buffer.Length == 12) { remoteLoRaAggregatorIp = receivedResults.RemoteEndPoint.Address; remoteLoRaAggregatorPort = receivedResults.RemoteEndPoint.Port; } try { MessageProcessor messageProcessor = new MessageProcessor(); _ = messageProcessor.processMessage(receivedResults.Buffer); } catch (Exception ex) { Console.WriteLine($"Error processing the message {ex.Message}"); } } }
void StartUdpListener() { m_udpListener = new UdpClient(new IPEndPoint(IPAddress.Any, 10500)) { EnableBroadcast = true, Client = { SendTimeout = 10000 } }; Task.Run(async() => { while (true) { await m_udpListener.SendAsync(new byte[64], 10, new IPEndPoint(IPAddress.Broadcast, 10500)); m_udpListener.ReceiveAsync(); if (m_udpListener.Available > 0) { var buffer = new byte[m_udpListener.Available]; m_udpListener.Client.Receive(buffer); string str = Encoding.ASCII.GetString(buffer); if (str == string.Empty) { continue; } var stream = new MemoryStream(); stream.Write(buffer, 0, buffer.Length); var serializer = new DataContractJsonSerializer(typeof(NetworkData)); NetworkData data = null; stream.Position = 0; data = (NetworkData)serializer.ReadObject(stream); m_client = new StreamSocket(); await m_client.ConnectAsync(new HostName(data.Message), "10501"); return; } } }); }
private async Task AutodiscoveryServer() { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "Nyx Hub Auto Responder"; } var hello = Encoding.UTF8.GetBytes("ACK"); _logger.Debug($"Starting autodiscover helper server at {IPAddress.Any}:{_hubPort + 10}...."); _runningServer = true; while (!_stop) { var server = new UdpClient(new IPEndPoint(IPAddress.Any, _hubPort + 10)); try { var msg = await server.ReceiveAsync(); var decoded = Encoding.UTF8.GetString(msg.Buffer); _logger.Debug($"Discovered by {msg.RemoteEndPoint}...."); await server.SendAsync(hello, hello.Length, msg.RemoteEndPoint); } catch (TaskCanceledException) { break; } catch (Exception e) { _logger.Trace($"Error on discovery: {e}"); } finally { server.Close(); } } _runningServer = false; }
public async Task <IResponse> Resolve(IRequest request) { using (UdpClient udp = InitUdpClient()) { await udp .SendAsync(request.ToArray(), request.Size, dns) .WithCancellationTimeout(timeout); UdpReceiveResult result = await udp.ReceiveAsync().WithCancellationTimeout(timeout); if (!result.RemoteEndPoint.Equals(dns)) { throw new IOException("Remote endpoint mismatch"); } byte[] buffer = result.Buffer; Response response = Response.FromArray(buffer); if (response.Truncated) { return(await fallback.Resolve(request)); } return(new ClientResponse(request, response, buffer)); } }
public async Task <IResponse> Resolve(IRequest request) { int retry = retries; IPEndPoint localEP = null; RETRY: using (UdpClient udp = (localEP == null ? new UdpClient() : new UdpClient(localEP))) { await udp .SendAsync(request.ToArray(), request.Size, dns) .WithCancellationTimeout(timeout); localEP = (IPEndPoint)udp.Client.LocalEndPoint; UdpReceiveResult result; try { result = await udp.ReceiveAsync().WithCancellationTimeout(timeout); if (!result.RemoteEndPoint.Equals(dns)) { throw new IOException("Remote endpoint mismatch"); } } catch (System.Exception) when(--retry > 0) { goto RETRY; } byte[] buffer = result.Buffer; Response response = Response.FromArray(buffer); if (response.Truncated) { return(await fallback.Resolve(request)); } return(new ClientResponse(request, response, buffer)); } }
public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress leftAddress, IPAddress rightAddress) { // TODO #5185: harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; using (var left = new UdpClient(new IPEndPoint(leftAddress, 0))) using (var right = new UdpClient(new IPEndPoint(rightAddress, 0))) { var leftEndpoint = (IPEndPoint)left.Client.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.Client.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); var receivedChecksums = new uint?[DatagramsToSend]; int receivedDatagrams = 0; Task receiverTask = Task.Run(async () => { for (; receivedDatagrams < DatagramsToSend; receivedDatagrams++) { UdpReceiveResult result = await left.ReceiveAsync(); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); Assert.Equal(DatagramSize, result.Buffer.Length); Assert.Equal(rightEndpoint, result.RemoteEndPoint); int datagramId = (int)result.Buffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(result.Buffer, 0, result.Buffer.Length); } }); var sentChecksums = new uint[DatagramsToSend]; int sentDatagrams = 0; Task senderTask = Task.Run(async () => { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (; sentDatagrams < DatagramsToSend; sentDatagrams++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; int sent = await right.SendAsync(sendBuffer, DatagramSize, leftEndpoint); Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); } }); Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } } }