Ejemplo n.º 1
0
        /// <summary>
        /// Continuously reads data from the websocket.
        /// </summary>
        public async Task HandleSocket()
        {
            try
            {
                var buffer = new byte[Utilities.Server.ReceiveBufferSize];
                WebSocketReceiveResult result = await ClientSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
                await ParseMessage(result, buffer);

                while (!ClientSocket.CloseStatus.HasValue)
                {
                    buffer = new byte[Utilities.Server.ReceiveBufferSize];
                    result = await ClientSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
                    await ParseMessage(result, buffer);
                }
                if (Utilities.Server.ClientList.Contains(this))
                {
                    Utilities.Server.ClientList.Remove(this);
                }
                await ClientSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            }
            catch (Exception ex)
            {
                if (Utilities.Server.ClientList.Contains(this))
                {
                    Utilities.Server.ClientList.Remove(this);
                }
                await ClientSocket.CloseOutputAsync(WebSocketCloseStatus.InternalServerError, "An unhandled exception occurred.", CancellationToken.None);

                SocketError?.Invoke(this, ex);
                SocketClosed?.Invoke(this, EventArgs.Empty);
                ClientSocket.Dispose();
            }
        }
Ejemplo n.º 2
0
 public async Task CloseAsync()
 {
     foreach (var item in _writeHandler)
     {
         item.Value.Event?.Set(null);
     }
     foreach (var item in _readHandler)
     {
         item.Value.Event?.Set(null);
     }
     await _socket.CloseAsync();
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Closes the connection and disposes the underlying socket
        /// </summary>
        /// <returns></returns>
        public async Task CloseAsync()
        {
            if (ClientSocket == null)
            {
                throw new InvalidOperationException("Socket not open");
            }

            await ClientSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

            await _listening;

            var socket = Socket;

            Socket = null;
            socket.Dispose();
        }