/// <summary> /// /// </summary> /// <param name="context"></param> private async void OnWebcamWebSocketContext(System.Net.WebSockets.HttpListenerWebSocketContext context) { WebSocket webSocket = null; try { // Get the current web socket. webSocket = context.WebSocket; CancellationTokenSource receiveCancelToken = new CancellationTokenSource(); byte[] receiveBuffer = new byte[READ_BUFFER_SIZE]; // While the WebSocket connection remains open run a // simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // Receive the next set of data. ArraySegment <byte> arrayBuffer = new ArraySegment <byte>(receiveBuffer); WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arrayBuffer, receiveCancelToken.Token); // If the connection has been closed. if (receiveResult.MessageType == WebSocketMessageType.Close) { break; } else { // Add the client _clients.GetOrAdd(context, webSocket); } } // Cancel the receive request. if (webSocket.State != WebSocketState.Open) { receiveCancelToken.Cancel(); } } catch { } finally { // Clean up by disposing the WebSocket. if (webSocket != null) { webSocket.Dispose(); } } }
public ListenerWebSocketTransport(HttpListenerWebSocketContext context) : base(context.WebSocket) { this.Principal = context.User; }
/// <summary> /// /// </summary> /// <param name="context"></param> private async void OnWebcamWebSocketContext(System.Net.WebSockets.HttpListenerWebSocketContext context) { WebSocket webSocket = null; try { // Get the current web socket. webSocket = context.WebSocket; CancellationTokenSource receiveCancelToken = new CancellationTokenSource(); byte[] receiveBuffer = new byte[READ_BUFFER_SIZE]; // While the WebSocket connection remains open run a // simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // Receive the next set of data. ArraySegment <byte> arrayBuffer = new ArraySegment <byte>(receiveBuffer); WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arrayBuffer, receiveCancelToken.Token); // If the connection has been closed. if (receiveResult.MessageType == WebSocketMessageType.Close) { break; } else { byte[] sound = null; Bitmap[] image = null; long audioPos = 0; long videoPos = 0; // Most of the time one image at a time. MemoryStream[] imageStream = new MemoryStream[10]; int imageStreamCount = 0; // Within this loop you can place a check if there are any clients // connected, and if none then stop capturing until some are connected. while ((_demuxHttp.ReadFrame(out sound, out image, out audioPos, out videoPos) > 0) && !_stopCapture) { // Has an image been captured. if (image != null && image.Length > 0) { // Create a memory stream for each image. imageStream[0] = new MemoryStream(); imageStreamCount++; // Save the image to the stream. image[0].Save(imageStream[0], System.Drawing.Imaging.ImageFormat.Jpeg); // data to send. byte[] result = imageStream[0].GetBuffer(); string base64 = Convert.ToBase64String(result); byte[] base64Bytes = Encoding.Default.GetBytes(base64); // Send a message back to the client indicating that // the message was recivied and was sent. await webSocket.SendAsync(new ArraySegment <byte>(base64Bytes), WebSocketMessageType.Text, true, CancellationToken.None); // Cleanup. image[0].Dispose(); imageStream[0].Dispose(); } } } } // Cancel the receive request. if (webSocket.State != WebSocketState.Open) { receiveCancelToken.Cancel(); } } catch { } finally { // Clean up by disposing the WebSocket. if (webSocket != null) { webSocket.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="context"></param> private void WebSocketServer_OnWebSocketContext(object sender, System.Net.WebSockets.HttpListenerWebSocketContext context) { OnWebcamWebSocketContext(context); }
private static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context, string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment <byte> internalBuffer) { HttpListenerWebSocketContext webSocketContext = null; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(null, context); } try { // get property will create a new response if one doesn't exist. HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client string origin = request.Headers[HttpKnownHeaderNames.Origin]; List <string> secWebSocketProtocols = new List <string>(); string outgoingSecWebSocketProtocolString; bool shouldSendSecWebSocketProtocolHeader = ProcessWebSocketProtocolHeader( request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol], subProtocol, out outgoingSecWebSocketProtocolString); if (shouldSendSecWebSocketProtocolHeader) { secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString); response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString); } // negotiate the websocket key return value string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken); response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept); response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101 response.ComputeCoreHeaders(); ulong hresult = SendWebSocketHeaders(response); if (hresult != 0) { throw new WebSocketException((int)hresult, SR.Format(SR.net_WebSockets_NativeSendResponseHeaders, nameof(AcceptWebSocketAsync), hresult)); } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(null, $"{HttpKnownHeaderNames.Origin} = {origin}"); NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketVersion} = {secWebSocketVersion}"); NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketKey} = {secWebSocketKey}"); NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketAccept} = {secWebSocketAccept}"); NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]}"); NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {outgoingSecWebSocketProtocolString}"); } await response.OutputStream.FlushAsync().SuppressContextFlow(); HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream."); ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode(); HttpRequestStream requestStream = new HttpRequestStream(context); requestStream.SwitchToOpaqueMode(); WebSocketHttpListenerDuplexStream webSocketStream = new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context); WebSocket webSocket = ServerWebSocket.Create(webSocketStream, subProtocol, receiveBufferSize, keepAliveInterval, internalBuffer); webSocketContext = new HttpListenerWebSocketContext( request.Url, request.Headers, request.Cookies, context.User, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, origin, secWebSocketProtocols.AsReadOnly(), secWebSocketVersion, secWebSocketKey, webSocket); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Associate(context, webSocketContext); NetEventSource.Associate(webSocketContext, webSocket); } } catch (Exception ex) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(context, ex); } throw; } finally { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(context); } } return(webSocketContext); }
internal static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context, string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment <byte>?internalBuffer = null) { ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval); // get property will create a new response if one doesn't exist. HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client string origin = request.Headers[HttpKnownHeaderNames.Origin]; string[] secWebSocketProtocols = null; string outgoingSecWebSocketProtocolString; bool shouldSendSecWebSocketProtocolHeader = ProcessWebSocketProtocolHeader( request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol], subProtocol, out outgoingSecWebSocketProtocolString); if (shouldSendSecWebSocketProtocolHeader) { secWebSocketProtocols = new string[] { outgoingSecWebSocketProtocolString }; response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString); } // negotiate the websocket key return value string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken); response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept); response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101 response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols); HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; // Send websocket handshake headers await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false); const int MinBufferSize = 14; // from ManagedWebSocket.MaxMessageHeaderLength Memory <byte> buffer = internalBuffer.GetValueOrDefault().Count >= MinBufferSize?internalBuffer.GetValueOrDefault() : // use provided buffer if it's big enough receiveBufferSize >= MinBufferSize ? new byte[receiveBufferSize] : // or use provided size if it's big enough Memory <byte> .Empty; // or use the default WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer: true, subProtocol, keepAliveInterval, buffer); HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext( request.Url, request.Headers, request.Cookies, context.User, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, origin, secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty <string>(), secWebSocketVersion, secWebSocketKey, webSocket); return(webSocketContext); }
public void HandleContext(HttpListenerWebSocketContext context) { throw new NotImplementedException(); }