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 } }
/** * 构造 */ public USocket(ISocketListener listener, Protocol protocol) { this.listener = listener; this.protocol = protocol; buf = new ByteBuf(4096); //queue = new BlockingQueue<ByteBuf>(5000); }
protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state) { if (IsStopped) return; ProcessNewClient(client, listener.Info.Security); }
/// <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); } } }
/// <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); } }
void OnListenerError(ISocketListener listener, Exception e) { var logger = this.AppServer.Logger; logger.Error(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e); }
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); }
/// <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); }
private void OnRequest(ISocketListener socketListener) { _logger.Debug("Client connected from {0}:{1}", socketListener.RemoteIpAddress, socketListener.RemotePort); AcceptRequest(); _engine.HandleRequest(socketListener); }
public void Start() { DoStart(); _startedTime = DateTime.UtcNow; _socketListener = CreateSocketListener(); _socketListener.ConnectionReceived += OnConnectionReceived; _socketListener.Bind(EndPoint); _started = true; }
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(); }
protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state) { if (IsStopped) { return; } ProcessNewClient(client, listener.Info.Security); }
protected void OnNewClientAccepted(ISocketListener listener, Socket client, object state) { if (IsStopped) { return; } ProcessNewClient(client); }
private void CreateListener() { if (_listener != null) { throw new Exception("Only one SocketListener is currently supported."); } _listener = ObjectFactory.GetInstance <ISocketListener>(); _listener.ServerSettings = _settings; }
/// <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(); }
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); }
/// <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(); }
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); }
/// <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; }
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; }
/// <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); } }
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()); }
//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>(); }
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())); }
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()); }
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)); }
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)); }
public ListenerStubFactory( ISocketListener listener ) { Listener = listener; }
public void Regiester(ISocketListener o) { _listenerList.Add(o); }
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(); }
void OnListenerError(ISocketListener listener, Exception e) { Logger.Error(string.Format("Listener ({0}) error: {1}", listener.Info.EndPoint, e.Message), e); }
protected abstract void OnSocketAccepted(ISocketListener listener, Socket socket);
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)); }
protected abstract void OnListenerError(ISocketListener listener, Exception ex);
protected abstract void OnNewClientAccepted(ISocketListener listener, Socket client, object state);
/** * 装入一个监听器 */ public void setListener(ISocketListener listener) { this.listener = listener; }
public ScgiServer(ISocketListener listener) { _listener = listener; }
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); }
/// <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); }
protected abstract void AcceptNewClient(ISocketListener listener, Socket client);
void listener_Error(ISocketListener listener, Exception e) { this.AppServer.Logger.Error(string.Format("Listener ({0}) error", listener.EndPoint), e); }
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); }
public void UnRegiester(ISocketListener o) { _listenerList.Remove(o); }