public async Task ConnectAsync(CoapClientConnectOptions options, CancellationToken cancellationToken)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _connectOptions = options;

            if (_dtlsClient != null)
            {
                _dtlsClient.OnDatagramReceived -= OnDatagramReceived;
                _dtlsClient.Dispose();
            }

            _udpClient?.Dispose();

            await ResolveIPEndpointAsync().ConfigureAwait(false);

            ConvertCredentials();

            // ! Match the local address family with the address family of the host!
            _udpClient  = new UdpClient(0, _ipEndPoint.AddressFamily);
            _dtlsClient = new Waher.Security.DTLS.DtlsOverUdp(_udpClient, Waher.Security.DTLS.DtlsMode.Client, null, null);
            _dtlsClient.OnDatagramReceived += OnDatagramReceived;
        }
Ejemplo n.º 2
0
        private void Initialize(IPEndPoint address, bool connect)
        {
            var resendThread = new Thread(ResendLoop)
            {
                Name = "PacketHandler"
            };

            resendThreadId = resendThread.ManagedThreadId;

            lock (sendLoopLock)
            {
                ClientId           = 0;
                ExitReason         = null;
                smoothedRtt        = MaxRetryInterval;
                smoothedRttVar     = TimeSpan.Zero;
                currentRto         = MaxRetryInterval;
                lastSentPingId     = 0;
                lastReceivedPingId = 0;
                lastMessageTimer.Restart();

                initPacketCheck = null;
                packetAckManager.Clear();
                receiveQueueCommand.Clear();
                receiveQueueCommandLow.Clear();
                receiveWindowVoice.Reset();
                receiveWindowVoiceWhisper.Reset();
                Array.Clear(packetCounter, 0, packetCounter.Length);
                Array.Clear(generationCounter, 0, generationCounter.Length);
                NetworkStats.Reset();

                udpClient?.Dispose();
                try
                {
                    if (connect)
                    {
                        remoteAddress = address;
                        udpClient     = new UdpClient(address.AddressFamily);
                        udpClient.Connect(address);
                    }
                    else
                    {
                        remoteAddress = null;
                        udpClient     = new UdpClient(address);
                    }
                }
                catch (SocketException ex) { throw new Ts3Exception("Could not connect", ex); }
            }

            try
            {
                resendThread.Start();
            }
            catch (SystemException ex) { throw new Ts3Exception("Error initializing internal stuctures", ex); }
        }
 public override void Dispose()
 {
     try
     {
         _client?.Dispose();
     }
     catch
     {
     }
     finally
     {
         _client = null;
     }
 }
Ejemplo n.º 4
0
 private void ThreadFunc()
 {
     Count = 0;
     try
     {
         Client = new UdpClient(Port);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString(), nameof(UdpCli), MessageBoxButton.OK, MessageBoxImage.Error);
     }
     try
     {
         while (Running)
         {
             IPEndPoint ep   = null;
             byte[]     bts  = Client.Receive(ref ep);
             DateTime   now  = DateTime.Now;
             string     data = Encoding.UTF8.GetString(bts);
             PacketReceived?.Invoke(now, Count, data);
             Count++;
         }
     }
     catch (ThreadAbortException) { }
     catch (SocketException) { }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString(), nameof(UdpCli), MessageBoxButton.OK, MessageBoxImage.Error);
     }
     finally
     {
         Client?.Dispose();
     }
 }
Ejemplo n.º 5
0
 public void Dispose()
 {
     if (_disposeSender)
     {
         _sender?.Dispose();
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UDPSocketPair"/> class.
        /// Creates two new UDP sockets using the start and end Port range
        /// </summary>
        public UDPSocketPair(int startPort, int endPort)
        {
            IsMulticast = false;

            // open a pair of UDP sockets - one for data (video or audio) and one for the status channel (RTCP messages)
            DataPort    = startPort;
            ControlPort = startPort + 1;

            bool ok = false;

            while (ok == false && (ControlPort < endPort))
            {
                // Video/Audio port must be odd and command even (next one)
                try
                {
                    dataSocket    = new UdpClient(DataPort);
                    controlSocket = new UdpClient(ControlPort);
                    ok            = true;
                }
                catch (SocketException)
                {
                    // Fail to allocate port, try again
                    dataSocket?.Dispose();
                    controlSocket?.Dispose();

                    // try next data or control port
                    DataPort    += 2;
                    ControlPort += 2;
                }
            }

            dataSocket.Client.ReceiveBufferSize = 100 * 1024;

            controlSocket.Client.DontFragment = false;
        }
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                    evt.Set();
                    receiveMain?.Join();
                    sendMain?.Join();
                    statsThread?.Join();
                    cancellationTokenSource?.Dispose();
                }

                sendUdpClient?.Dispose();
                receiveUdpClient?.Dispose();
                evt?.Dispose();
            }

            disposed = true;
        }
        public void Dispose()
        {
            _cancellationTokenSource.Cancel();

            _broadcastSocket?.Dispose();
            _listenerSocket?.Dispose();
        }
Ejemplo n.º 9
0
        public override void Dispose()
        {
            Close();

            senderClient?.Dispose();
            listenerClient?.Dispose();
        }
Ejemplo n.º 10
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _udpClient?.Dispose();
     }
 }
Ejemplo n.º 11
0
 public void Dispose()
 {
     _cancellationTokenSource?.Cancel();
     _cancellationTokenSource.Dispose();
     _readerThread?.Join();
     _udpClient?.Dispose();
 }
Ejemplo n.º 12
0
        void InternalStop()
        {
            Running = false;

            sendclient?.Dispose();
            srvclient?.Dispose();
        }
Ejemplo n.º 13
0
    public void Stop()
    {
        Logger.LogDebug("SlMessageSystem.Stop", "");
        try
        {
            _cts.Cancel();

            foreach (Circuit circuit in CircuitByEndPoint.Values)
            {
                circuit.Stop();
            }

            _cts.Dispose();
            UdpClient.Close();
            UdpClient?.Dispose();
        }
        catch (ObjectDisposedException e)
        {
            // We do nothing here.
        }
        catch (Exception e)
        {
            Logger.LogError("SlMessageSystem.Stop", e.Message);
        }
    }
Ejemplo n.º 14
0
 private void DisposeConnections()
 {
     m_tcpClient?.Dispose();
     m_udpClient?.Dispose();
     m_serialClient?.Dispose();
     m_modbusConnection?.Dispose();
 }
        /// <summary>
        /// UDP connection helper method
        /// </summary>
        /// <returns></returns>
        public bool Connect(string hostName, string portNumber)
        {
            try
            {
                if (string.IsNullOrEmpty(hostName) || string.IsNullOrEmpty(portNumber))
                {
                    throw new ArgumentNullException("Host Name or Port");
                }

                int mPort;
                if (!int.TryParse(portNumber, out mPort))
                {
                    throw new InvalidOperationException($"Port is not a number: {portNumber}");
                }

                client?.Close();
                client?.Dispose();

                client = new UdpClient(mPort);
                client.Connect(hostName, mPort);
                Login(client);

                return(true);
            }
            catch
            {
                if (!(client == null))
                {
                    client.Close();
                }
                throw;
            }
        }
Ejemplo n.º 16
0
 internal void UnInitialize()
 {
     sender?.Dispose();
     receiver?.Dispose();
     sender         = null;
     receiver       = null;
     remoteEndPoint = null;
 }
Ejemplo n.º 17
0
        public void CloseSocket()
        {
#if UDP
            _udpClient?.Dispose();
#endif
            Options.Default.GameSocket.Off();
            Options.Default.GameSocket.Close();
        }
Ejemplo n.º 18
0
 protected override void Dispose(bool disposing)
 {
     if (!IsDisposed)
     {
         _client?.Dispose();
         base.Dispose(disposing);
     }
 }
Ejemplo n.º 19
0
 public void Dispose()
 {
     _client?.Dispose();
     _nodeQueue?.Dispose();
     _recvMessageQueue?.Dispose();
     _sendMessageQueue?.Dispose();
     _replyMessageQueue?.Dispose();
 }
Ejemplo n.º 20
0
        private string Query(byte[] commandBytes)
        {
            var commandAsString = Encoding.UTF8.GetString(commandBytes);

            _logger.LogInformation("Executing {command} command against {hostname}:{port}", commandAsString, Hostname, QueryPort);

            UdpClient udpClient = null;

            try
            {
                var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                udpClient = new UdpClient(QueryPort)
                {
                    Client = { SendTimeout = 5000, ReceiveTimeout = 5000 }
                };
                udpClient.Connect(Hostname, QueryPort);
                udpClient.Send(commandBytes, commandBytes.Length);

                var datagrams = new List <string>();
                do
                {
                    var datagramBytes = udpClient.Receive(ref remoteIpEndPoint);
                    var datagramText  = Encoding.Default.GetString(datagramBytes);

                    datagrams.Add(datagramText);

                    if (udpClient.Available == 0)
                    {
                        Thread.Sleep(500);
                    }
                } while (udpClient.Available > 0);

                var responseText = new StringBuilder();

                foreach (var datagram in datagrams)
                {
                    var text = datagram;
                    if (text.IndexOf("print", StringComparison.Ordinal) == 4)
                    {
                        text = text.Substring(10);
                    }

                    responseText.Append(text);
                }

                return(responseText.ToString());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to execute {command} against {hostname}:{port}", commandAsString, Hostname, QueryPort);
                throw;
            }
            finally
            {
                udpClient?.Dispose();
            }
        }
 public void Disconnect()
 {
     if (!_connected)
     {
         return;
     }
     _client?.Dispose();
     _connected = false;
 }
Ejemplo n.º 22
0
 internal void Stop()
 {
     lock (_lockObject)
     {
         _udpTokenSource?.Cancel();
         _udpClient?.Dispose();
         _udpClient = null;
     }
 }
 public void Dispose()
 {
     if (!IsDisposed)
     {
         IsDisposed = true;
         SendMessageToGameClient?.Dispose();
         ReceiveMessageFromGameClient?.Dispose();
     }
 }
 public void Dispose()
 {
     _client?.Dispose();
     _task?.Dispose();
     _tokenSource?.Cancel();
     _tokenSource?.Dispose();
     _tokenSource2?.Cancel();
     _tokenSource2?.Dispose();
 }
Ejemplo n.º 25
0
 public void Stop()
 {
     // s?.Dispose();
     // s = null;
     tun?.Deinit();
     u?.Dispose();
     u = null;
     _ = outPackets.Writer.TryComplete();
 }
Ejemplo n.º 26
0
        public Task StopAsync()
        {
            _listenerThreadCancel.Cancel();
            _listenerThread = null;
            _udpClient?.Dispose();
            _udpClient = null;

            return(Task.CompletedTask);
        }
Ejemplo n.º 27
0
 public void Dispose()
 {
     try
     {
         _UdpClient?.Dispose();
     }
     catch
     {
     }
 }
Ejemplo n.º 28
0
 public void Dispose()
 {
     _stop = true;
     Robustness.Instance.SafeCall(() => { _udpClient?.Dispose(); });
     Robustness.Instance.SafeCall(() =>
     {
         _receiveThread?.Interrupt();
         _receiveThread?.Abort();
     });
 }
Ejemplo n.º 29
0
 public void Stop()
 {
     try
     {
         Active = false;
         UdpClient?.Close();
         UdpClient?.Dispose();
     }
     catch { }
 }
Ejemplo n.º 30
0
 /// <inheritdoc />
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         unicastClientIp4?.Dispose();
         unicastClientIp6?.Dispose();
         NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
         Stop();
     }
 }