Example #1
0
        private async Task SetupClient(Socket client)
        {
            lock (_pending)
            {
                _pending.Add(client);
            }

            _logger.LogVerbose(Properties.Resources.TcpNetworkListener_ConnectionLogString, _localEndpoint);

            StreamSocketDataAdapter  da = new StreamSocketDataAdapter(client, _localEndpoint.ToString());
            ClientConnectedEventArgs e  = new ClientConnectedEventArgs(da);

            NetUtils.PopulateBagFromSocket(client, e.Properties);

            try
            {
                await Task.Run(() => ClientConnected.Invoke(this, e));
            }
            catch
            {
                client.Dispose();
            }
            finally
            {
                lock (_pending)
                {
                    _pending.Remove(client);
                }
            }
        }
Example #2
0
        private async Task ReceiveCallback()
        {
            while (true)
            {
                try
                {
                    var result = await _clientSocket.ReceiveAsync();

                    bool       bNewConnection = false;
                    IPEndPoint ep             = result.RemoteEndPoint;

                    lock (_conns)
                    {
                        if (!_conns.ContainsKey(result.RemoteEndPoint))
                        {
                            _logger.LogVerbose(Properties.Resources.UdpNetworkListener_ConnectionLogString, ep);
                            _conns.Add(ep, new LockedQueue <byte[]>());
                            bNewConnection = true;
                        }
                    }

                    _conns[ep].Enqueue(result.Buffer);
                    if (bNewConnection && (ClientConnected != null))
                    {
                        ClientConnectedEventArgs args =
                            new ClientConnectedEventArgs(new UdpServerDataAdapter(this, ep));
                        NetUtils.PopulateBagFromSocket(_clientSocket.Client, args.Properties);
                        ClientConnected.Invoke(this, args);
                    }
                }
                catch (SocketException ex)
                {
                    // For a server this just means the thing we last sent to ignored us
                    // Should possibly reopen the connection?
                    if (ex.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        ReopenConnection();
                    }
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
            }
        }
Example #3
0
        private void ReceiveCallback(IAsyncResult res)
        {
            GeneralUtils.SetThreadCulture();

            if (res.IsCompleted)
            {
                try
                {
                    IPEndPoint ep             = null;
                    bool       bNewConnection = false;
                    UdpClient  client         = (UdpClient)res.AsyncState;

                    byte[] data = null;

                    try
                    {
                        data = client.EndReceive(res, ref ep);
                    }
                    catch (SocketException ex)
                    {
                        // For a server this just means the thing we last sent to ignored us
                        // Should possibly reopen the connection?
                        if ((SocketError)ex.ErrorCode == SocketError.ConnectionReset)
                        {
                            ReopenConnection();
                            client = _clientSocket;
                        }
                        else
                        {
                            // Rethrow
                            throw;
                        }
                    }

                    try
                    {
                        client.BeginReceive(ReceiveCallback, client);
                    }
                    catch (SocketException ex)
                    {
                        // For a server this just means the thing we last sent to ignored us
                        if ((SocketError)ex.ErrorCode == SocketError.ConnectionReset)
                        {
                            ReopenConnection();
                            client = _clientSocket;
                            client.BeginReceive(ReceiveCallback, client);
                        }
                        else
                        {
                            // Rethrow
                            throw;
                        }
                    }

                    if (data != null)
                    {
                        lock (_conns)
                        {
                            if (!_conns.ContainsKey(ep))
                            {
                                _logger.LogVerbose(CANAPE.Net.Properties.Resources.UdpNetworkListener_ConnectionLogString, ep);

                                _conns.Add(ep, new LockedQueue <byte[]>());
                                bNewConnection = true;
                            }
                        }

                        _conns[ep].Enqueue(data);

                        if (bNewConnection && (ClientConnected != null))
                        {
                            ClientConnectedEventArgs args = new ClientConnectedEventArgs(new UdpServerDataAdapter(this, ep));

                            NetUtils.PopulateBagFromSocket(_clientSocket.Client, args.Properties);

                            ClientConnected.Invoke(this, args);
                        }
                    }
                }
                catch (SocketException)
                {
                }
                catch (ObjectDisposedException)
                {
                }
            }
        }
        private void CreateInstance()
        {
            EventHandler<ClientConnectedEventArgs> clientConnected = ClientConnected;
            if (clientConnected != null)
            {
                SerialPort port = _port;

                if (port != null)
                {
                    ClientConnectedEventArgs e = new ClientConnectedEventArgs(new SerialPortDataAdapter(port));

                    clientConnected(this, e);
                }
            }
        }
Example #5
0
            private void Poll()
            {
                // Not much point if no event handler
                if (ClientConnected != null)
                {
                    NetGraph[] graphs = _service.Connections;

                    int newConnections = _document._concurrentConnections - graphs.Length;

                    long currTicks = DateTime.UtcNow.Ticks;

                    if (_document._specifyTimeout && (_document._timeoutMilliSeconds >= 0))
                    {
                        TimeSpan span = new TimeSpan(currTicks);
                        foreach (NetGraph graph in graphs)
                        {
                            if (span.Subtract(graph.CreatedTicks).TotalMilliseconds >= (double)_document._timeoutMilliSeconds)
                            {
                                _service.CloseConnection(graph);

                                // Add another connection
                                newConnections++;
                            }
                        }
                    }

                    if (_document._limitConnections)
                    {
                        newConnections = Math.Min(_connsLeft, newConnections);
                    }

                    while (newConnections > 0)
                    {
                        IDataAdapter adapter = new DataEndpointAdapter(
                            _document._factory.Create(_logger, new MetaDictionary(), _document._globalMeta), _logger);

                        ClientConnectedEventArgs args = new ClientConnectedEventArgs(adapter);

                        args.Properties.AddValue("ConnectionNumber", System.Threading.Interlocked.Increment(ref _connCount));

                        ClientConnected(this, new ClientConnectedEventArgs(adapter));

                        newConnections--;
                        if (_connsLeft > 0)
                        {
                            _connsLeft--;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (_document._limitConnections && (_connsLeft == 0) && (_service.Connections.Length == 0))
                    {
                        // Don't reenable timer
                        _logger.LogInfo("Completed {0} connections", _document._totalConnections);
                    }
                    else
                    {
                        _timer.Start();
                    }
                }
            }
Example #6
0
        /// <summary>
        /// Method called when a new client connects
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClientConnected(object sender, ClientConnectedEventArgs e)
        {
            NetGraph graph = ConnectClient(e.DataAdapter, e.Properties);

            if (graph == null)
            {
                e.DataAdapter.Close();
            }
        }
Example #7
0
        private void ReceiveCallback(IAsyncResult res)
        {
            GeneralUtils.SetThreadCulture();

            if (res.IsCompleted)
            {
                try
                {
                    IPEndPoint ep = null;
                    bool bNewConnection = false;
                    UdpClient client = (UdpClient)res.AsyncState;

                    byte[] data = null;

                    try
                    {
                        data = client.EndReceive(res, ref ep);
                    }
                    catch (SocketException ex)
                    {
                        // For a server this just means the thing we last sent to ignored us
                        // Should possibly reopen the connection?
                        if ((SocketError)ex.ErrorCode == SocketError.ConnectionReset)
                        {
                            ReopenConnection();
                            client = _clientSocket;
                        }
                        else
                        {
                            // Rethrow
                            throw;
                        }
                    }

                    try
                    {
                        client.BeginReceive(ReceiveCallback, client);
                    }
                    catch (SocketException ex)
                    {
                        // For a server this just means the thing we last sent to ignored us
                        if ((SocketError)ex.ErrorCode == SocketError.ConnectionReset)
                        {
                            ReopenConnection();
                            client = _clientSocket;
                            client.BeginReceive(ReceiveCallback, client);
                        }
                        else
                        {
                            // Rethrow
                            throw;
                        }
                    }

                    if (data != null)
                    {
                        lock (_conns)
                        {
                            if (!_conns.ContainsKey(ep))
                            {
                                _logger.LogVerbose(CANAPE.Net.Properties.Resources.UdpNetworkListener_ConnectionLogString, ep);

                                _conns.Add(ep, new LockedQueue<byte[]>());
                                bNewConnection = true;
                            }
                        }

                        _conns[ep].Enqueue(data);

                        if (bNewConnection && (ClientConnected != null))
                        {
                            ClientConnectedEventArgs args = new ClientConnectedEventArgs(new UdpServerDataAdapter(this, ep));

                            NetUtils.PopulateBagFromSocket(_clientSocket.Client, args.Properties);

                            ClientConnected.Invoke(this, args);
                        }
                    }
                }
                catch (SocketException)
                {
                }
                catch (ObjectDisposedException)
                {
                }
            }
        }
Example #8
0
        private void AcceptCallback(IAsyncResult res)
        {
            GeneralUtils.SetThreadCulture();

            if (res.IsCompleted)
            {
                try
                {
                    TcpListener listener = ((TcpListener)res.AsyncState);

                    TcpClient client = null;

                    try
                    {
                        client = listener.EndAcceptTcpClient(res);
                        client.NoDelay = _nodelay;
                    }
                    finally
                    {
                        // Restart it
                        if (_isStarted)
                        {
                            listener.BeginAcceptTcpClient(AcceptCallback, listener);
                        }
                    }

                    if (ClientConnected != null)
                    {
                        lock (_pending)
                        {
                            _pending.Add(client);
                        }

                        _logger.LogVerbose(CANAPE.Net.Properties.Resources.TcpNetworkListener_ConnectionLogString, client.Client.RemoteEndPoint);

                        TcpClientDataAdapter da = new TcpClientDataAdapter(client);
                        ClientConnectedEventArgs e = new ClientConnectedEventArgs(da);
                        NetUtils.PopulateBagFromSocket(client.Client, e.Properties);

                        ClientConnected.Invoke(this, e);

                        lock (_pending)
                        {
                            _pending.Remove(client);
                        }
                    }
                    else
                    {
                        // There was noone to accept the message, so just close
                        client.Close();
                    }
                }
                catch (ObjectDisposedException)
                {
                    // Don't do anything
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex);
                }
            }
        }
Example #9
0
        private void AcceptCallback(IAsyncResult res)
        {
            GeneralUtils.SetThreadCulture();

            if (res.IsCompleted)
            {
                try
                {
                    TcpListener listener = ((TcpListener)res.AsyncState);

                    TcpClient client = null;

                    try
                    {
                        client         = listener.EndAcceptTcpClient(res);
                        client.NoDelay = _nodelay;
                    }
                    finally
                    {
                        // Restart it
                        if (_isStarted)
                        {
                            listener.BeginAcceptTcpClient(AcceptCallback, listener);
                        }
                    }

                    if (ClientConnected != null)
                    {
                        lock (_pending)
                        {
                            _pending.Add(client);
                        }

                        _logger.LogVerbose(CANAPE.Net.Properties.Resources.TcpNetworkListener_ConnectionLogString, client.Client.RemoteEndPoint);

                        TcpClientDataAdapter     da = new TcpClientDataAdapter(client);
                        ClientConnectedEventArgs e  = new ClientConnectedEventArgs(da);
                        NetUtils.PopulateBagFromSocket(client.Client, e.Properties);

                        ClientConnected.Invoke(this, e);

                        lock (_pending)
                        {
                            _pending.Remove(client);
                        }
                    }
                    else
                    {
                        // There was noone to accept the message, so just close
                        client.Close();
                    }
                }
                catch (ObjectDisposedException)
                {
                    // Don't do anything
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex);
                }
            }
        }