public Communicator(int serverPort, INetworkClient client, INetworkListener listener)
 {
     ServerName = Environment.MachineName;
     ServerPort = serverPort;
     Client     = client;
     Listener   = listener;
 }
Beispiel #2
0
        /// <summary>
        /// Method responsible to connect client in server.
        /// </summary>
        /// <param name="ip">The ip address from server.</param>
        /// <param name="port">The port number from server, the default value us 7171</param>
        /// <param name="listenerType">The listener type to creation of listener, the default value is NetworkListenerType.TCP.</param>
        /// <param name="maxMessageBuffer">The max length of message buffer, the default value is 4096.</param>
        /// <returns>The boolean value of client connection.</returns>
        public bool Connect(string ip, ushort port = 7171, NetworkListenerType listenerType = NetworkListenerType.TCP, ushort maxMessageBuffer = 4096)
        {
            try
            {
                if (listenerType == NetworkListenerType.TCP)
                {
                    _networkListener = new TcpNetworkListener(OnMessageReceived, OnDisconnected);
                }
                else if (listenerType == NetworkListenerType.UDP)
                {
                    _networkListener = new UdpNetworkListener(OnMessageReceived, OnDisconnected);
                }
                else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText)
                {
                    _networkListener = new WSNetworkListener(listenerType, OnMessageReceived, OnDisconnected);
                }

                _clientThread = new Thread(() =>
                {
                    _networkListener.StartClient(ip, port, maxMessageBuffer);
                });

                _clientThread.IsBackground = true;
                _clientThread.Start();

                Thread.Sleep(15); // Delay for socket connection.
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }

            return(HasConnected);
        }
Beispiel #3
0
 public void AddListener(INetworkListener listener)
 {
     lock (m_listeners)
     {
         m_listeners.Add(listener);
     }
 }
Beispiel #4
0
 public void RemoveListener(INetworkListener listener)
 {
     lock (m_listeners)
     {
         m_listeners.Remove(listener);
     }
 }
Beispiel #5
0
 private void Initialize(int listenPort, INetworkListener transportListener, Envelope messageEnvelope)
 {
     Port     = listenPort;
     listener = transportListener;
     Envelope = messageEnvelope;
     listener.Initialize(Port);
 }
Beispiel #6
0
        public virtual async ValueTask BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
        {
            if (endpoint is IPEndPoint ipEndpoint)
            {
                _ipEndpoint = ipEndpoint;
            }
            else
            {
                throw new NotSupportedException("Only IPEndPoint are currently supported by inline sockets.");
            }

            _logger.BindListenSocket(_ipEndpoint);

            _listener = _networkProvider.CreateListener(new NetworkListenerSettings
            {
                IPEndPoint          = _ipEndpoint,
                AllowNatTraversal   = _options.AllowNatTraversal,
                ExclusiveAddressUse = _options.ExclusiveAddressUse,
                ListenerBacklog     = _options.ListenBacklog,
                NoDelay             = _options.NoDelay,
            });

            // the only way to cancel a call to accept a socket is to stop the listener.
            // this is okay, because this call is cancelled only when the listener is about to be
            // unbound and disposed anyway.
            _listenerCancellationCallback = _listener.Stop;

            _listener.Start();
        }
Beispiel #7
0
        private async Task Run()
        {
            INetworkListener listener = _serviceProvider.GetService <INetworkListener>();
            await listener.Listen(43594);

            Console.ReadKey();
        }
Beispiel #8
0
        /// <summary>
        /// Method responsible for start the async network listener.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token for the task execution.</param>
        /// <param name="listenerType">The listener type to creation of listener, the default value is NetworkListenerType.TCP.</param>
        private async Task StartListenerAsync(CancellationToken cancellationToken, NetworkListenerType listenerType = NetworkListenerType.TCP)
        {
            try
            {
                if (listenerType == NetworkListenerType.TCP)
                {
                    _networkListener = new TcpNetworkListener(_port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer);
                }
                else if (listenerType == NetworkListenerType.UDP)
                {
                    _networkListener = new UdpNetworkListener(_port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer);
                }
                else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText)
                {
                    _networkListener = new WebSocketNetworkListener(listenerType, _port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer);
                }

                OnServerStartedHandler?.Invoke();

                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
Beispiel #9
0
        /// <summary>
        /// Listen indefinitely for network connections on the specified port.
        /// </summary>
        private async Task ListenForConnectionsAsync()
        {
            INetworkListener listener = null;

            try
            {
                var noDelay = Options?.TcpNoDelay ?? DicomServiceOptions.Default.TcpNoDelay;

                listener = NetworkManager.CreateNetworkListener(IPAddress, Port);
                await listener.StartAsync().ConfigureAwait(false);

                IsListening = true;

                while (!_cancellationSource.IsCancellationRequested)
                {
                    await _hasNonMaxServicesFlag.WaitAsync().ConfigureAwait(false);

                    var networkStream = await listener
                                        .AcceptNetworkStreamAsync(_certificateName, noDelay, _cancellationSource.Token)
                                        .ConfigureAwait(false);

                    if (networkStream != null)
                    {
                        var scp = CreateScp(networkStream);
                        if (Options != null)
                        {
                            scp.Options = Options;
                        }

                        var serviceTask = scp.RunAsync();
                        lock (_services)
                        {
                            _services.Add(new RunningDicomService(scp, serviceTask));
                        }

                        _hasServicesFlag.Set();
                        if (IsServicesAtMax)
                        {
                            _hasNonMaxServicesFlag.Reset();
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception e)
            {
                Logger.Error("Exception listening for DICOM services, {@error}", e);

                Stop();
                Exception = e;
            }
            finally
            {
                listener?.Stop();
                IsListening = false;
            }
        }
Beispiel #10
0
 public void SetListener(INetworkListener listener)
 {
     if (listener != null)
     {
         this.listener = listener;
         State         = ConnectingState.NeverConnect;
         Connect();
     }
 }
Beispiel #11
0
 public AcceptState(IClientEntry new_client, string remote_endpoint,
                    string local_endpoint, INetworkListener listener, Exception exception)
 {
     NewClient      = new_client;
     RemoteEndpoint = remote_endpoint;
     LocalEndpoint  = local_endpoint;
     Listener       = listener;
     Exception      = exception;
 }
Beispiel #12
0
        private void Initialize()
        {
            rtcpNetworkListener = new UdpListener(rtpSession.RtcpEndPoint, RtpSession.DefaultNetworkTimeout * 2);

            threadRtcpListener = new Thread(new ThreadStart(ListenThread));
            threadRtcpListener.IsBackground = true;
            threadRtcpListener.Name         = "RtcpListener";

            threadRtcpListener.Start();
        }
Beispiel #13
0
 private static void AddListener(List <string> builder, INetworkListener listener)
 {
     if (listener is AggregateNetworkListener)
     {
         AddAggregateListener(builder, (AggregateNetworkListener)listener);
     }
     else
     {
         builder.Add(listener.ToString());
     }
 }
Beispiel #14
0
        /// <summary>
        /// Clean up the RtcpListener
        ///
        /// A thread will not abort until it is in the running state.  Our listening thread is
        /// generally blocked by the call to rtcpNetworkListener.ReceiveFrom().  In order to
        /// dispose things quickly and efficiently, we tell the listening thread to abort as soon
        /// as it is back in the running state.  Then we clean up the network listener which should
        /// unblock us.
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            lock (this)
            {
                disposed = true;

                threadRtcpListener.Abort();
                threadRtcpListener = null;

                rtcpNetworkListener.Dispose();
                rtcpNetworkListener = null;
            }
        }
 private void InitializeNetwork()
 {
     if (Utility.IsMulticast(groupEP) && (!nextHopEP.Equals(groupEP)))
     {
         // reflector based session
         rtpNetworkListener = new UdpListener(groupEP, nextHopEP, RtpSession.DefaultNetworkTimeout);
     }
     else
     {
         // multicast or direct unicast: no reflector needed
         rtpNetworkListener = new UdpListener(nextHopEP, RtpSession.DefaultNetworkTimeout);
     }
 }
Beispiel #16
0
    public void RemoveListener(INetworkListener l)
    {
        for (int i = 0; i < networkListeners.Count; i++)
        {
            INetworkListener nl = networkListeners[i].Target as INetworkListener;
            if (nl != l)
            {
                continue;
            }

            networkListeners.RemoveAt(i);
            i--;
        }
    }
Beispiel #17
0
        public void AddListener(INetworkListener listener, bool start)
        {
            if (this.Disposed)
            {
                throw new ObjectDisposedException(nameof(NetworkManager));
            }

            this.NetworkListeners.Add(listener);

            NetworkManager.Logger.Info($"Listener binded on {listener.Bind} was added");

            if (start)
            {
                listener.StartListening();
            }
        }
Beispiel #18
0
    public void Update()
    {
        //process received messages
        {
            List <DataPackage> received = null;
            lock (receiveBuffer)
            {
                received = new List <DataPackage>(receiveBuffer);
                receiveBuffer.Clear();
            }

            for (int i = 0; i < networkListeners.Count; i++)
            {
                INetworkListener nl = networkListeners[i].Target as INetworkListener;
                if (nl == null)
                {
                    networkListeners.RemoveAt(i);
                    i--;
                }
                else
                {
                    foreach (DataPackage dp in received)
                    {
                        nl.OnDataReceived(dp);
                    }
                }
            }
        }

        if (!hasToken)
        {
            return;
        }

        while (queue.Count != 0)
        {
            DataPackage dp = queue[0];
            queue.RemoveAt(0);
            WriteAll(dp);
        }

        hasToken = false;
        Write(nextClient, new TokenChangePackage());
    }
Beispiel #19
0
        private void Initialize()
        {
            if (Utility.IsMulticast(groupEP) && (!nextHopEP.Equals(groupEP)))
            {
                // use reflector
                rtcpNetworkListener = new UdpListener(groupEP, nextHopEP, RtpSession.DefaultNetworkTimeout * 2);
            }
            else
            {
                // multicast or direct unicast
                rtcpNetworkListener = new UdpListener(nextHopEP, RtpSession.DefaultNetworkTimeout * 2);
            }

            threadRtcpListener = new Thread(new ThreadStart(ListenThread));
            threadRtcpListener.IsBackground = true;
            threadRtcpListener.Name         = "RtcpListener";

            threadRtcpListener.Start();
        }
Beispiel #20
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="factory"></param>
        /// <param name="logger"></param>
        /// <param name="globalMeta"></param>
        /// <param name="proxyServer"></param>
        /// <param name="proxyClient"></param>
        /// <param name="filters"></param>
        /// <param name="defaultTimeout"></param>
        /// <param name="afterdata"></param>
        public ProxyNetworkService(INetworkListener listener, NetGraphFactory factory, Logger logger,
                                   MetaDictionary globalMeta,
                                   ProxyServer proxyServer, ProxyClient proxyClient, ProxyFilter[] filters, int defaultTimeout, bool afterdata)
        {
            _packetLog = new List <LogPacket>(1000);
            _logger    = logger;
            Listener   = listener;

            _factory        = factory;
            _connections    = new List <ConnectionEntry>();
            _globalMeta     = globalMeta;
            _history        = new List <ConnectionHistoryEntry>();
            _subServices    = new List <ProxyNetworkService>();
            DefaultBinding  = NetworkLayerBinding.Default;
            _proxyClient    = proxyClient;
            _proxyServer    = proxyServer;
            _filters        = filters;
            _defaultTimeout = defaultTimeout;
            _afterData      = afterdata;
        }
        public virtual async ValueTask BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
        {
            _endpoint = endpoint;
            _logger.BindListenSocket(_endpoint);

            _listener = _networkProvider.CreateListener(new NetworkListenerSettings
            {
                EndPoint            = _endpoint,
                AllowNatTraversal   = _options.AllowNatTraversal,
                ExclusiveAddressUse = _options.ExclusiveAddressUse,
                ListenerBacklog     = _options.ListenBacklog,
                NoDelay             = _options.NoDelay,
            });

            // the only way to cancel a call to accept a socket is to stop the listener.
            // this is okay, because this call is cancelled only when the listener is about to be
            // unbound and disposed anyway.
            _listenerCancellationCallback = _listener.Stop;

            _listener.Start();
        }
Beispiel #22
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="packetLog"></param>
        /// <param name="listener"></param>
        /// <param name="factory"></param>
        /// <param name="logger"></param>
        /// <param name="globalMeta"></param>
        /// <param name="history"></param>
        /// <param name="credentials"></param>
        /// <param name="proxyServer"></param>
        /// <param name="proxyClient"></param>
        /// <param name="filters"></param>
        /// <param name="defaultTimeout"></param>
        /// <param name="afterdata"></param>
        public ProxyNetworkService(IList <LogPacket> packetLog, INetworkListener listener, NetGraphFactory factory, Logger logger,
                                   MetaDictionary globalMeta, IList <ConnectionHistoryEntry> history, IDictionary <SecurityPrincipal, ICredentialObject> credentials,
                                   ProxyServer proxyServer, ProxyClient proxyClient, ProxyFilter[] filters, int defaultTimeout, bool afterdata)
        {
            _packetLog = packetLog;
            _logger    = logger;
            Listener   = listener;

            _factory           = factory;
            _connections       = new List <ConnectionEntry>();
            _globalMeta        = globalMeta;
            _history           = history;
            _subServices       = new List <ProxyNetworkService>();
            DefaultBinding     = NetworkLayerBinding.Default;
            _credentials       = new Dictionary <SecurityPrincipal, ICredentialObject>(credentials);
            _credentialManager = new CredentialsManagerService();
            _credentialManager.ResolveCredentials += _credentialManager_ResolveCredentials;
            _proxyClient    = proxyClient;
            _proxyServer    = proxyServer;
            _filters        = filters;
            _defaultTimeout = defaultTimeout;
            _afterData      = afterdata;
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="left">The left listener</param>
 /// <param name="right">The right listener</param>
 public AggregateNetworkListener(INetworkListener left, INetworkListener right)
 {
     _left = left;
     _right = right;
 }
Beispiel #24
0
        /// <summary>
        /// Clean up the RtcpListener
        /// 
        /// A thread will not abort until it is in the running state.  Our listening thread is
        /// generally blocked by the call to rtcpNetworkListener.ReceiveFrom().  In order to
        /// dispose things quickly and efficiently, we tell the listening thread to abort as soon 
        /// as it is back in the running state.  Then we clean up the network listener which should
        /// unblock us.  
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            lock(this)
            {
                disposed = true;
                
                threadRtcpListener.Abort();
                threadRtcpListener = null;

                rtcpNetworkListener.Dispose();
                rtcpNetworkListener = null;
            }
        }
Beispiel #25
0
        private void Initialize()
        {
            rtcpNetworkListener = new UdpListener(rtpSession.RtcpEndPoint, RtpSession.DefaultNetworkTimeout * 2);

            threadRtcpListener = new Thread(new ThreadStart(ListenThread));
            threadRtcpListener.IsBackground = true;
            threadRtcpListener.Name = "RtcpListener";
            
            threadRtcpListener.Start();
        }
Beispiel #26
0
 public SocketServer(MessageRegistry registry)
 {
     listener      = new SocketListener();
     this.registry = registry;
 }
Beispiel #27
0
        private void Initialize()
        {
           
            if (Utility.IsMulticast(groupEP) && (!nextHopEP.Equals(groupEP)))
            {
                // use reflector
                rtcpNetworkListener = new UdpListener(groupEP, nextHopEP, RtpSession.DefaultNetworkTimeout * 2);
            }
            else
            {
                // multicast or direct unicast
                rtcpNetworkListener = new UdpListener(nextHopEP, RtpSession.DefaultNetworkTimeout * 2);
            }

            threadRtcpListener = new Thread(new ThreadStart(ListenThread));
            threadRtcpListener.IsBackground = true;
            threadRtcpListener.Name = "RtcpListener";
            
            threadRtcpListener.Start();
        }
Beispiel #28
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="left">The left listener</param>
 /// <param name="right">The right listener</param>
 public AggregateNetworkListener(INetworkListener left, INetworkListener right)
 {
     _left  = left;
     _right = right;
 }
Beispiel #29
0
 private void DisposeNetwork()
 {
     rtpNetworkListener.Dispose();
     rtpNetworkListener = null;
 }
Beispiel #30
0
    public void RemoveListener(INetworkListener l)
    {
        for (int i = 0; i < networkListeners.Count; i++)
        {
            INetworkListener nl = networkListeners[i].Target as INetworkListener;
            if (nl != l)
                continue;

            networkListeners.RemoveAt(i);
            i--;
        }
    }
Beispiel #31
0
 public void AddListener(INetworkListener l)
 {
     networkListeners.Add(new WeakReference(l));
 }
Beispiel #32
0
 private void InitializeNetwork()
 {
     rtpNetworkListener = new UdpListener(rtpSession.RtpEndPoint, RtpSession.DefaultNetworkTimeout);
 }
        /// <summary>
        /// Create the base service
        /// </summary>
        /// <param name="logger">The logger to use</param>
        /// <returns>The new network service</returns>
        public override ProxyNetworkService Create(Logger logger)
        {
            ProxyNetworkService ret = null;

            if (logger == null)
            {
                logger = Logger.SystemLogger;
            }

            if ((LocalPort < 0) || (LocalPort > 65535))
            {
                throw new NetServiceException(Properties.Resources.NetServerDocument_ValidPort);
            }
            else if (ServerFactory == null)
            {
                throw new NetServiceException(Properties.Resources.NetServerDocument_MustSpecifyServer);
            }
            else
            {
                try
                {
                    ProxyServer server = new PassThroughProxyServer(logger, Layers);

                    ProxyClient client = new NetServerProxyClient(ServerFactory);

                    INetworkListener listener = null;

                    if (!UdpEnable)
                    {
                        if (NetUtils.OSSupportsIPv4)
                        {
                            listener = new TcpNetworkListener(AnyBind, false, LocalPort, logger, false);
                        }

                        if (Ipv6Bind && NetUtils.OSSupportsIPv6)
                        {
                            INetworkListener ipv6Listener = new TcpNetworkListener(AnyBind, true, LocalPort, logger, false);

                            if (listener != null)
                            {
                                listener = new AggregateNetworkListener(listener, ipv6Listener);
                            }
                            else
                            {
                                listener = ipv6Listener;
                            }
                        }
                    }
                    else
                    {
                        if (NetUtils.OSSupportsIPv4)
                        {
                            listener = new UdpNetworkListener(AnyBind, false, LocalPort, EnableBroadcast, logger);
                        }

                        if (Ipv6Bind && NetUtils.OSSupportsIPv6)
                        {
                            INetworkListener ipv6Listener = new UdpNetworkListener(AnyBind, true, LocalPort, EnableBroadcast, logger);

                            if (listener != null)
                            {
                                listener = new AggregateNetworkListener(listener, ipv6Listener);
                            }
                            else
                            {
                                listener = ipv6Listener;
                            }
                        }
                    }

                    if (listener == null)
                    {
                        throw new NetServiceException(Properties.Resources.NetServiceDocument_CannotSetupListener);
                    }

                    ret = new ProxyNetworkService(listener,
                                                  Graph ?? BuildDefaultProxyFactory(), logger, _globalMeta,
                                                  server, client, null, Timeout.Infinite, false);

                    ret.DefaultBinding = NetworkLayerBinding.Server;
                }
                catch (SocketException ex)
                {
                    throw new NetServiceException(Properties.Resources.NetServerDocument_ErrorCreatingServer, ex);
                }
                catch (IOException ex)
                {
                    throw new NetServiceException(Properties.Resources.NetServerDocument_ErrorCreatingServer, ex);
                }

                return(ret);
            }
        }
Beispiel #34
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="packetLog"></param>
        /// <param name="listener"></param>
        /// <param name="factory"></param>
        /// <param name="logger"></param>
        /// <param name="globalMeta"></param>
        /// <param name="history"></param>
        /// <param name="credentials"></param>
        /// <param name="proxyServer"></param>
        /// <param name="proxyClient"></param>
        /// <param name="filters"></param>
        /// <param name="defaultTimeout"></param>
        /// <param name="afterdata"></param>
        public ProxyNetworkService(IList<LogPacket> packetLog, INetworkListener listener, NetGraphFactory factory, Logger logger, 
            MetaDictionary globalMeta, IList<ConnectionHistoryEntry> history, IDictionary<SecurityPrincipal, ICredentialObject> credentials, 
            ProxyServer proxyServer, ProxyClient proxyClient, ProxyFilter[] filters, int defaultTimeout, bool afterdata)
        {
            _packetLog = packetLog;
            _logger = logger;
            Listener = listener;

            _factory = factory;
            _connections = new List<ConnectionEntry>();
            _globalMeta = globalMeta;
            _history = history;
            _subServices = new List<ProxyNetworkService>();
            DefaultBinding = NetworkLayerBinding.Default;
            _credentials = new Dictionary<SecurityPrincipal, ICredentialObject>(credentials);
            _credentialManager = new CredentialsManagerService();
            _credentialManager.ResolveCredentials += _credentialManager_ResolveCredentials;
            _proxyClient = proxyClient;
            _proxyServer = proxyServer;
            _filters = filters;
            _defaultTimeout = defaultTimeout;
            _afterData = afterdata;
        }
Beispiel #35
0
 public virtual void Dispose()
 {
     _listener?.Dispose();
     _listener = null;
     _listenerCancellationCallback = null;
 }
 private void DisposeNetwork()
 {
     rtpNetworkListener.Dispose();
     rtpNetworkListener = null;
 }
Beispiel #37
0
 private void InitializeNetwork()
 {
     rtpNetworkListener = new UdpListener(rtpSession.RtpEndPoint, RtpSession.DefaultNetworkTimeout);
 }
Beispiel #38
0
 public SocketServer(IPAddress address, MessageRegistry registry)
 {
     listener = new SocketListener(address);
     this.registry = registry;
 }
 private static void AddListener(List<string> builder, INetworkListener listener)
 {
     if (listener is AggregateNetworkListener)
     {
         AddAggregateListener(builder, (AggregateNetworkListener)listener);
     }
     else
     {
         builder.Add(listener.ToString());
     }
 }
Beispiel #40
0
 public SocketServer(IPAddress address, MessageRegistry registry)
 {
     listener      = new SocketListener(address);
     this.registry = registry;
 }
Beispiel #41
0
 public void AddListener(INetworkListener l)
 {
     networkListeners.Add(new WeakReference(l));
 }
Beispiel #42
0
 public SocketServer(MessageRegistry registry)
 {
     listener = new SocketListener();
     this.registry = registry;
 }
Beispiel #43
0
 public void SetListener(INetworkListener l)
 {
     _listener = l;
     _responceListener = l;
     _connectionListener = l;
 }
Beispiel #44
0
 private void InitializeNetwork()
 {
     if (Utility.IsMulticast(groupEP) && (!nextHopEP.Equals(groupEP)))
     {
         // reflector based session
         rtpNetworkListener = new UdpListener(groupEP, nextHopEP, RtpSession.DefaultNetworkTimeout);
     }
     else
     {
         // multicast or direct unicast: no reflector needed
         rtpNetworkListener = new UdpListener(nextHopEP, RtpSession.DefaultNetworkTimeout);
     }
 }