public async Task <Connection> EstablishConnectionAsync() { SocketWrapper closableWrapper = null; try { Stream stream = null; #if TARGET_BROWSER closableWrapper = new SocketWrapper(_listenSocket); stream = new WebSocketStream(_listenSocket, ownsSocket: true); #else var socket = await _listenSocket.AcceptAsync().ConfigureAwait(false); closableWrapper = new SocketWrapper(socket); try { socket.NoDelay = true; } // OSX can throw if socket is in weird state during close or cancellation catch (SocketException ex) when(ex.SocketErrorCode == SocketError.InvalidArgument && PlatformDetection.IsOSXLike) { } stream = new NetworkStream(socket, ownsSocket: false); #endif return(await Connection.CreateAsync(closableWrapper, stream, _options).ConfigureAwait(false)); } catch (Exception) { closableWrapper?.Close(); throw; } }