示例#1
0
        /// <summary>
        /// Block and asynchronously accept new WebSocket connections.
        /// </summary>
        /// <param name="limit">The maximum amount of clients the server will accept.</param>
        /// <param name="ct">A cancellation token that when cancelled, stops new clients from being accepted, </param>
        /// <param name="services">Services used to inject dependencies into connection handlers.</param>
        /// <returns></returns>
        public async Task AcceptConnectionsAsync <THandler>(int limit, CancellationToken ct, IServiceProvider services = null)
            where THandler : HandlerBase <HandlerContext>
        {
            limiter = new SemaphoreSlim(limit);

            try
            {
                tcp.Start();
                while (!ct.IsCancellationRequested)
                {
                    await limiter.WaitAsync().ConfigureAwait(false);

                    var networkStream = await GetNetworkStreamAsync(tcp).ConfigureAwait(false);

                    var connection = new WsLiteConnection(Guid.NewGuid(), config, networkStream, ct);

                    clients.Add(connection);

                    var handler = Activator.CreateInstance <THandler>();
                    handler.SetContext(new HandlerContext(this, connection, services));
                    connection.OnMessage += handler.HandleMessageAsync;
                    connection.OnLog     += handler.HandleLogAsync;
                    connection.OnError   += handler.HandleErrorAsync;

                    #pragma warning disable CS4014
                    connection.HandshakeAsync().ConfigureAwait(false);
                    #pragma warning restore CS4014
                }
            }
            finally
            {
                foreach (var client in clients)
                {
                    client.Dispose();
                }
                tcp.Stop();
            }
        }
示例#2
0
 /// <summary>
 /// Remove the connection from the clients list, and dispose the underlying stream.
 /// </summary>
 /// <param name="connection"></param>
 public void Disconnect(WsLiteConnection connection)
 {
     using (connection)
         clients.Remove(connection);
 }