private void Run() { Log.Debug("Started communicator"); var remoteEndPoint = new IPEndPoint(IPAddress.Any, EndPoint.Port); using (var udp = new UdpClient(_endPoint)) { udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout); while (true) { if (Token.IsCancellationRequested) { Log.Debug("Received request to stop"); return; } try { if (udp.Available > 0) { var data = udp.Receive(ref remoteEndPoint); if (data.Length > 0) { try { var message = Converter.DeSerialize(data); OnEnvelope?.Invoke(new Envelope(message, remoteEndPoint)); } catch (Exception ex) { Log.Error(ex.Message); } } } } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.TimedOut) { Log.Debug(ex.Message); } } catch (Exception ex) { Log.Debug(ex.Message); } finally { while (OutgoingEnvelopes.Count > 0) { // Log.DebugFormat("Attempting to send 1 of {0} envelopes to send", OutgoingEnvelopes.Count); Envelope envelopeToSend; if (OutgoingEnvelopes.TryDequeue(out envelopeToSend)) { var bytes = Converter.Serialize(envelopeToSend.MessageContent); try { // Log.DebugFormat("Attempting to send {0} bytes", bytes.Length); udp.Send(bytes, bytes.Length, envelopeToSend.EndPoint); } catch (SocketException ex) { Log.Error(ex.Message); } } } } } } }
public void SendEnvelope(Envelope env) { env.MessageContent.MessageCount++; OnEnvelope?.Invoke (new Envelope(env.MessageContent, EndPoint)); }