static async Task <bool> connectAsync(string uri, CancellationToken token, Action <Connection> onConnection, Action <ClientWebSocketOptions> setOptions = null) { ClientWebSocket webSocket = null; var isClosedSuccessfully = true; try { webSocket = new ClientWebSocket(); setOptions?.Invoke(webSocket.Options); await webSocket.ConnectAsync(new Uri(uri), token); } catch (Exception) { webSocket?.Dispose(); throw; } var connection = new Connection(webSocket, CookieUtils.GetCookies(webSocket.Options.Cookies?.GetCookies(new Uri(uri)))); try { onConnection(connection); await connection.ListenReceiveAsync(token); } finally { isClosedSuccessfully = webSocket.State != WebSocketState.Aborted; webSocket?.Dispose(); } return(isClosedSuccessfully); }
static async Task handleSocketAsync(HttpListenerContext ctx, CancellationToken token, Action <Connection, WebSocketContext> onConnect) { if (!ctx.Request.IsWebSocketRequest) { return; } WebSocketContext wsCtx = null; WebSocket webSocket = null; try { wsCtx = await ctx.AcceptWebSocketAsync(subProtocol : null); webSocket = wsCtx.WebSocket; } catch (Exception) { ctx.Response.StatusCode = (int)HttpStatusCode.InternalServerError; ctx.Response.Close(); return; } var connection = new Connection(webSocket, CookieUtils.GetCookies(wsCtx.CookieCollection)); try { lock (connections) connections.Add(connection); onConnect(connection, wsCtx); await connection.ListenReceiveAsync(token); } catch (Exception ex) { connection.InvokeOnError(ex); } finally { webSocket?.Dispose(); lock (connections) connections.Remove(connection); } }