Exemplo n.º 1
0
        void Receive()
        {
            var token = cts.Token;

            try
            {
                ISocketListener listener = CreateListener();
                listener.Start();
                using (token.Register(listener.Stop))
                {
                    while (isRunning)
                    {
                        using (var client = listener.AcceptClient())
                        {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            ProcessClient(client);
                        }
                    }
                }
            }
            catch (SocketException)
            {
                // stoped receiving
            }
        }
Exemplo n.º 2
0
 /**
  * 构造
  */
 public USocket(ISocketListener listener, Protocol protocol)
 {
     this.listener = listener;
     this.protocol = protocol;
     buf           = new ByteBuf(4096);
     //queue = new BlockingQueue<ByteBuf>(5000);
 }
Exemplo n.º 3
0
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            if (IsStopped)
                return;

            ProcessNewClient(client, listener.Info.Security);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Called when [new client accepted].
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <param name="client">The client.</param>
        /// <param name="state">The state.</param>
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            var paramArray = state as object[];

            var receivedData   = paramArray[0] as byte[];
            var socketAddress  = paramArray[1] as SocketAddress;
            var remoteEndPoint = (socketAddress.Family == AddressFamily.InterNetworkV6 ? m_EndPointIPv6.Create(socketAddress) : m_EndPointIPv4.Create(socketAddress)) as IPEndPoint;

            try
            {
                if (m_IsUdpRequestInfo)
                {
                    ProcessPackageWithSessionID(client, remoteEndPoint, receivedData);
                }
                else
                {
                    ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData);
                }
            }
            catch (Exception e)
            {
                if (AppServer.Logger.IsErrorEnabled)
                {
                    AppServer.Logger.Error("Process UDP package error!", e);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Called when [new client accepted].
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <param name="client">The client.</param>
        /// <param name="state">The state.</param>
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            var eventArgs = state as SocketAsyncEventArgs;

            var remoteEndPoint = eventArgs.RemoteEndPoint as IPEndPoint;
            var receivedData   = new ArraySegment <byte>(eventArgs.Buffer, eventArgs.Offset, eventArgs.BytesTransferred);

            try
            {
                if (m_IsUdpRequestInfo)
                {
                    ProcessPackageWithSessionID(client, remoteEndPoint, receivedData);
                }
                else
                {
                    ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData);
                }
            }
            catch (Exception e)
            {
                if (AppServer.Logger.IsErrorEnabled)
                {
                    AppServer.Logger.Error("Process UDP package error!", e);
                }
            }
            finally
            {
                SaePool.Return(eventArgs.UserToken as SaeState);
            }
        }
Exemplo n.º 6
0
        void OnListenerError(ISocketListener listener, Exception e)
        {
            var logger = this.AppServer.Logger;


            logger.Error(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e);
        }
Exemplo n.º 7
0
        void OnListenerError(ISocketListener listener, Exception e)
        {
            listener.Stop();

            var logger = this.AppServer.Logger;

            if (!logger.IsErrorEnabled)
            {
                return;
            }

            if (e is ObjectDisposedException || e is NullReferenceException)
            {
                return;
            }

            var socketException = e as SocketException;

            if (socketException != null)
            {
                if (socketException.ErrorCode == 995 || socketException.ErrorCode == 10004 || socketException.ErrorCode == 10038)
                {
                    return;
                }
            }

            logger.ErrorFormat(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e);
        }
Exemplo n.º 8
0
 /// <summary>
 /// socket accepted handler
 /// </summary>
 /// <param name="listener"></param>
 /// <param name="connection"></param>
 private void listener_Accepted(ISocketListener listener, SocketBase.IConnection connection)
 {
     if (base._listConnections.Count() > this._maxConnections)
     {
         connection.BeginDisconnect(); return;
     }
     base.RegisterConnection(connection);
 }
Exemplo n.º 9
0
        private void OnRequest(ISocketListener socketListener)
        {
            _logger.Debug("Client connected from {0}:{1}", socketListener.RemoteIpAddress, socketListener.RemotePort);

            AcceptRequest();

            _engine.HandleRequest(socketListener);
        }
Exemplo n.º 10
0
 public void Start()
 {
     DoStart();
     _startedTime    = DateTime.UtcNow;
     _socketListener = CreateSocketListener();
     _socketListener.ConnectionReceived += OnConnectionReceived;
     _socketListener.Bind(EndPoint);
     _started = true;
 }
Exemplo n.º 11
0
        public HttpServer(int port, ISocketListener socketListener)
        {
            this.Port           = port;
            this.socketListener = socketListener;
            this.socketListener.ConnectionReceived += this.ConnectionReceivedAsync;

            this.requestQueue      = new ProducerConsumerQueue(WORKER_COUNT);
            this.fileSystemHandler = new FileSystemHandler();
        }
Exemplo n.º 12
0
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            if (IsStopped)
            {
                return;
            }

            ProcessNewClient(client, listener.Info.Security);
        }
Exemplo n.º 13
0
        protected void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            if (IsStopped)
            {
                return;
            }

            ProcessNewClient(client);
        }
Exemplo n.º 14
0
        private void CreateListener()
        {
            if (_listener != null)
            {
                throw new Exception("Only one SocketListener is currently supported.");
            }

            _listener = ObjectFactory.GetInstance <ISocketListener>();
            _listener.ServerSettings = _settings;
        }
Exemplo n.º 15
0
        /// <summary>
        /// socket accepted handler
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="connection"></param>
        private void OnAccepted(ISocketListener listener, SocketBase.IConnection connection)
        {
            if (base.CountConnection() < this._maxConnections)
            {
                base.RegisterConnection(connection);
                return;
            }

            SocketBase.Log.Trace.Info("too many connections.");
            connection.BeginDisconnect();
        }
Exemplo n.º 16
0
        void OnListenerError(ISocketListener listener, Exception e)
        {
            var logger = this.AppServer.Logger;

            if (!logger.IsErrorEnabled)
            {
                return;
            }

            logger.ErrorFormat(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e);
        }
Exemplo n.º 17
0
        /// <summary>
        /// socket accepted handler
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="connection"></param>
        private void OnAccepted(ISocketListener<TMessageInfo, TMessage> listener, SocketBase.IConnection<TMessageInfo, TMessage> connection)
        {
            if (base.CountConnection() < this._maxConnections)
            {
                connection.SetProtoHandler(_protocolHandlerFactory.CreateProtocolHandler());
                base.RegisterConnection(connection);
                return;
            }

            SocketBase.Log.Trace.Info("too many connections.");
            connection.BeginDisconnect();
        }
Exemplo n.º 18
0
        public void HandleRequest(ISocketListener socketListener)
        {
            if (!_hostConfiguration.Scheme.IsSecure())
            {
                _styxEngine.HandleRequest(socketListener);
                return;
            }

            _logger.Info("Authenticating Secure Connection");
            var authenticated = socketListener.Authenticate(_hostConfiguration.Certificate);
            authenticated.ContinueWith(_ => _styxEngine.HandleRequest(socketListener), TaskContinuationOptions.OnlyOnRanToCompletion);
            authenticated.ContinueWith(_ => OnError(_.Exception, socketListener), TaskContinuationOptions.OnlyOnFaulted);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Executed on clientconnection closed
 /// </summary>
 /// <param name="listener">Listener to send events to</param>
 /// <param name="client">Client socket being closed</param>
 private void CloseClientConnection(ISocketListener listener, Socket client)
 {
     if (client.Connected)
     {
         listener.OnClose(this);
         client.Close();
         this.Clients.Remove(client.GetHashCode());
     }
     else
     {
         client.Dispose();
         this.Clients.Remove(client.GetHashCode());
     }
 }
        public void Dispose()
        {
            _listener?.Dispose();
            _listener = null;

            var clients = _cluster.GetSnapshot();

            foreach (var client in clients)
            {
                client.Dispose();
            }
            _cluster.Clear();
            _cluster = null;
        }
Exemplo n.º 21
0
        public StyxHost(Uri location, IHostConfiguration hostConfiguration = null, ILogger logger = null, IBootstrapper bootstrapper = null)
        {
            if (location == null)
                throw new ArgumentNullException("location");

            hostConfiguration = hostConfiguration ?? new HostConfiguration();
            hostConfiguration.Port = location.Port;
            hostConfiguration.Scheme = location.Scheme;
            logger = logger ?? new DebuggerLogger();
            bootstrapper = bootstrapper ?? new TinyIoCBootstrapper(hostConfiguration, logger);
            _hostConfiguration = bootstrapper.HostConfiguration;
            _logger = bootstrapper.Logger;
            _engine = bootstrapper.Engine;
            _routeRegister = bootstrapper.RouteRegister;
            _listenerSocket = bootstrapper.SocketListener;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Called when [new client accepted].
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <param name="client">The client.</param>
        /// <param name="state">The state.</param>
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            var paramArray = state as object[];

            var receivedData = paramArray[0] as byte[];
            var socketAddress = paramArray[1] as SocketAddress;
            var remoteEndPoint = (socketAddress.Family == AddressFamily.InterNetworkV6 ? m_EndPointIPv6.Create(socketAddress) : m_EndPointIPv4.Create(socketAddress)) as IPEndPoint;

            if (m_IsUdpRequestInfo)
            {
                ProcessPackageWithSessionID(client, remoteEndPoint, receivedData);
            }
            else
            {
                ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData);
            }
        }
Exemplo n.º 23
0
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            if (IsStopped)
            {
                return;
            }

            //Get the socket for the accepted client connection and put it into the
            //ReadEventArg object user token
            SocketAsyncEventArgsProxy socketEventArgsProxy;

            if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
            {
                AppServer.AsyncRun(client.SafeClose);
                if (AppServer.Logger.IsErrorEnabled)
                {
                    AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber);
                }
                return;
            }

            ISocketSession session;

            var security = listener.Info.Security;

            if (security == SslProtocols.None)
            {
                session = RegisterSession(client, new AsyncSocketSession(client, socketEventArgsProxy));
            }
            else
            {
                session = RegisterSession(client, new AsyncStreamSocketSession(client, security, socketEventArgsProxy));
            }

            if (session == null)
            {
                socketEventArgsProxy.Reset();
                this.m_ReadWritePool.Push(socketEventArgsProxy);
                AppServer.AsyncRun(client.SafeClose);
                return;
            }

            session.Closed += SessionClosed;
            AppServer.AsyncRun(() => session.Start());
        }
Exemplo n.º 24
0
        //private bool _fileIsUploading;
        //private IUploadingFile _currentUploadingFile;

        #endregion

        #region Constructors

        public Server(ISocketConnection connection)
        {
            ConnectedClients = new List <IClient>();
            Connection       = connection;

            _dataConverter = new DataConverter(Encoding.ASCII);

            _listener = new SocketListener(connection /*, _dataConverter*/);
            _listener.DataReceived    += OnDataReceived;
            _listener.ClientConnected += OnClientConnected;

            _clientMessageToServerMessageConverter = MessageConverter.Instance;
            _fileManager    = FileManager.GetInstance("Upload");
            _messageManager = MessageManager.GetInstance(_dataConverter, _fileManager);
            _dataToClientMessageConverter =
                ClientDataConverter.GetInstance(_clientMessageToServerMessageConverter.MessageEnd);

            //UploadingFiles = new List<IUploadingFile>();
        }
Exemplo n.º 25
0
        private void Read(ISocketListener socketListener, byte[] buffer, IHandler handler)
        {
            if (!socketListener.IsListening)
                return;

            socketListener.Receive(buffer, readBytes =>
            {
                if (readBytes.Length <= 0)
                {
                    _logger.Debug("Client disconnected from {0}:{1}", socketListener.RemoteIpAddress, socketListener.RemotePort);
                    socketListener.Close(_logger, handler);
                    return;
                }

                handler.Receive(readBytes);

                Read(socketListener, buffer, handler);
            }, ex => socketListener.Close(_logger, handler, ex.GetWebSocketErrorCode()));
        }
Exemplo n.º 26
0
        protected override void AcceptNewClient(ISocketListener listener, Socket client)
        {
            if(Interlocked.Increment(ref m_CurrentConnectionCount) > AppServer.Config.MaxConnectionNumber)
            {
                Interlocked.Decrement(ref m_CurrentConnectionCount);
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                return;
            }

            var session = RegisterSession(client, new AsyncStreamSocketSession(client));

            if (session == null)
            {
                Interlocked.Decrement(ref m_CurrentConnectionCount);
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                return;
            }

            session.Closed += new EventHandler<SocketSessionClosedEventArgs>(session_Closed);
            Async.Run(() => session.Start());
        }
        protected override void AcceptNewClient(ISocketListener listener, Socket client)
        {
            if (Interlocked.Increment(ref m_CurrentConnectionCount) > AppServer.Config.MaxConnectionNumber)
            {
                Interlocked.Decrement(ref m_CurrentConnectionCount);
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                return;
            }

            var session = RegisterSession(client, new AsyncStreamSocketSession(client));

            if (session == null)
            {
                Interlocked.Decrement(ref m_CurrentConnectionCount);
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                return;
            }

            session.Closed += new EventHandler <SocketSessionClosedEventArgs>(session_Closed);
            Async.Run(() => session.Start());
        }
Exemplo n.º 28
0
        public void HandleRequest(ISocketListener socketListener)
        {
            var buffer = new byte[ReadSize];

            socketListener.Receive(buffer, readBytes =>
            {
                if (readBytes.Length <= 0)
                {
                    _logger.Debug("Client disconnected from {0}:{1}", socketListener.RemoteIpAddress, socketListener.RemotePort);
                    socketListener.Dispose();
                    return;
                }

                var requestString = Encoding.UTF8.GetString(readBytes);

                var request = _requestParser.Parse(requestString);

                var handler = _handshakeNegotiator.Negotiate(request, m => socketListener.Send(m, _logger));

                Read(socketListener, buffer, handler);
            }, ex => socketListener.Close(ex.GetErrorResponse(), _logger));
        }
Exemplo n.º 29
0
        protected override void AcceptNewClient(ISocketListener listener, Socket client)
        {
            if (IsStopped)
                return;

            //Get the socket for the accepted client connection and put it into the 
            //ReadEventArg object user token
            SocketAsyncEventArgsProxy socketEventArgsProxy;
            if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
            {
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                if (AppServer.Logger.IsErrorEnabled)
                    AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber);
                return;
            }

            ISocketSession session;

            var security = listener.Info.Security;

            if (security == SslProtocols.None)
                session = RegisterSession(client, new AsyncSocketSession(client, socketEventArgsProxy));
            else
                session = RegisterSession(client, new AsyncStreamSocketSession(client, security, socketEventArgsProxy));

            if (session == null)
            {
                socketEventArgsProxy.Reset();
                this.m_ReadWritePool.Push(socketEventArgsProxy);
                Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                return;
            }

            session.Closed += session_Closed;
            Async.Run(() => session.Start());
        }
 public SocketManager(ISocketListener socketListener, ISocketCluster mainCluster)
 {
     _listener = socketListener ?? throw new ArgumentNullException(nameof(socketListener));
     _cluster  = mainCluster ?? throw new ArgumentNullException(nameof(mainCluster));
 }
 public SocketManager(int backlog, EndPoint endPoint, SocketFactory sf, ISocketCluster mainCluster)
 {
     _listener = sf?.CreateListenerSocket(endPoint, backlog) ?? throw new ArgumentNullException(nameof(sf));
     _cluster  = mainCluster ?? throw new ArgumentNullException(nameof(mainCluster));
 }
Exemplo n.º 32
0
 public ListenerStubFactory( ISocketListener listener )
 {
     Listener = listener;
 }
Exemplo n.º 33
0
 public void Regiester(ISocketListener o)
 {
     _listenerList.Add(o);
 }
Exemplo n.º 34
0
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            if (IsStopped)
                return;

            //Get the socket for the accepted client connection and put it into the
            //ReadEventArg object user token
            SocketAsyncEventArgsProxy socketEventArgsProxy;
            if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
            {
                AppServer.AsyncRun(client.SafeClose);
                if (AppServer.Logger.IsErrorEnabled)
                    AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber);
                return;
            }

            ISocketSession socketSession;

            var security = listener.Info.Security;

            if (security == SslProtocols.None)
                socketSession = new AsyncSocketSession(client, socketEventArgsProxy);
            else
                socketSession = new AsyncStreamSocketSession(client, security, socketEventArgsProxy);

            var session = CreateSession(client, socketSession);

            if (session == null)
            {
                socketEventArgsProxy.Reset();
                this.m_ReadWritePool.Push(socketEventArgsProxy);
                AppServer.AsyncRun(client.SafeClose);
                return;
            }

            socketSession.Closed += SessionClosed;

            var negotiateSession = socketSession as INegotiateSocketSession;

            if (negotiateSession == null)
            {
                if (RegisterSession(session))
                {
                    AppServer.AsyncRun(() => socketSession.Start());
                }

                return;
            }

            negotiateSession.NegotiateCompleted += OnSocketSessionNegotiateCompleted;
            negotiateSession.Negotiate();
        }
Exemplo n.º 35
0
 void OnListenerError(ISocketListener listener, Exception e)
 {
     Logger.Error(string.Format("Listener ({0}) error: {1}", listener.Info.EndPoint, e.Message), e);
 }
Exemplo n.º 36
0
 protected abstract void OnSocketAccepted(ISocketListener listener, Socket socket);
Exemplo n.º 37
0
 private void OnError(Exception e, ISocketListener socketListener)
 {
     _logger.Error("Failed to authenticate secure connection. {0}", e);
     var forbidden = new HttpResponse(HttpStatusCode.Forbidden);
     socketListener.Send(forbidden.ToBytes(), socketListener.Dispose, ex => _logger.Error("Failed to response to client: {0}", ex));
 }
Exemplo n.º 38
0
 protected abstract void OnListenerError(ISocketListener listener, Exception ex);
Exemplo n.º 39
0
 protected abstract void OnNewClientAccepted(ISocketListener listener, Socket client, object state);
Exemplo n.º 40
0
 /**
  * 装入一个监听器
  */
 public void setListener(ISocketListener listener)
 {
     this.listener = listener;
 }
Exemplo n.º 41
0
 public ScgiServer(ISocketListener listener)
 {
     _listener = listener;
 }
Exemplo n.º 42
0
        void OnListenerError(ISocketListener listener, Exception e)
        {
            var logger = this.AppServer.Logger;

            if(!logger.IsErrorEnabled)
                return;

            if (e is ObjectDisposedException || e is NullReferenceException)
                return;

            var socketException = e as SocketException;

            if (socketException != null)
            {
                if (socketException.ErrorCode == 995 || socketException.ErrorCode == 10004 || socketException.ErrorCode == 10038)
                    return;
            }

            logger.ErrorFormat(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e);
        }
Exemplo n.º 43
0
 protected abstract void OnNewClientAccepted(ISocketListener listener, Socket client, object state);
Exemplo n.º 44
0
 /// <summary>
 /// socket accepted handler
 /// </summary>
 /// <param name="listener"></param>
 /// <param name="connection"></param>
 private void listener_Accepted(ISocketListener listener, IConnection connection)
 {
     if (base._listConnections.Count() > this._maxConnections)
     {
         connection.BeginDisconnect(); return;
     }
     base.RegisterConnection(connection);
 }
Exemplo n.º 45
0
 protected abstract void AcceptNewClient(ISocketListener listener, Socket client);
Exemplo n.º 46
0
 void listener_Error(ISocketListener listener, Exception e)
 {
     this.AppServer.Logger.Error(string.Format("Listener ({0}) error", listener.EndPoint), e);
 }
Exemplo n.º 47
0
        void OnListenerError(ISocketListener listener, Exception e)
        {
            var logger = this.AppServer.Logger;

            if(!logger.IsErrorEnabled)
                return;

            logger.Error(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e);
        }
Exemplo n.º 48
0
 public void UnRegiester(ISocketListener o)
 {
     _listenerList.Remove(o);
 }