public AcceptWebSocketAsync ( string subProtocol ) : Task |
||
subProtocol | string | |
Результат | Task |
private async void HandleRequest(HttpListenerContext context) { Console.WriteLine("New Session."); var ws = (await context.AcceptWebSocketAsync(subProtocol: null)).WebSocket; clients.Add(ws); while (ws.State == WebSocketState.Open) { try { var buf = new ArraySegment<byte>(new byte[1024]); var ret = await ws.ReceiveAsync(buf, System.Threading.CancellationToken.None); if (ret.MessageType == WebSocketMessageType.Close) { Console.WriteLine("Session Close."); break; } Console.WriteLine("Got Message."); } catch { break; } } clients.Remove(ws); ws.Dispose(); }
public async Task<bool> HandleAsync(HttpListenerContext context) { if (context.Request.IsWebSocketRequest) { var webSocketContext = await context.AcceptWebSocketAsync(null); var protocolStream = new DebugStream(new WebSocketStream(webSocketContext.WebSocket)); var protocol = _protocolProvider.GetProtocol(protocolStream); var delayPerFrame = 1000 / _maximumFramesPerSecond; using (var screen = _screenProvider.GetScreen()) { await protocol.StartAsync(screen.GetFrame(Timeout.Infinite)); while (true) { var beginTime = DateTime.Now.Ticks; var screenFrame = screen.GetFrame(0); if (screenFrame != null && (screenFrame.ModifiedRegions.Length > 0 || screenFrame.MovedRegions.Length > 0)) { await protocol.UpdateAsync(screenFrame); } var elapsedTime = (int) ((DateTime.Now.Ticks - beginTime) / TimeSpan.TicksPerSecond); if (elapsedTime < delayPerFrame) await Task.Delay(delayPerFrame - elapsedTime); } } } return false; }
private async void ContextHandler(HttpListenerContext context) { var request = context.Request; Console.WriteLine("{0} {1} {2}", request.RemoteEndPoint.Address, request.HttpMethod, request.Url); if (request.IsWebSocketRequest) webSocketServer.HandleContext(await context.AcceptWebSocketAsync(webSocketServer.Protocol)); else httpServer.HandleContext(context); }
public async Task GetResponseAsync(HttpListenerContext context, string localBaseUrl, string remoteBaseUrl, CancellationToken ct) { string postUri = null; if (context.Request.IsWebSocketRequest) { UriBuilder ub = new UriBuilder(PostUri) { Scheme = "wss" }; postUri = ub.Uri.ToString(); } else { postUri = PostUri.ToString(); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUri); request.Method = context.Request.HttpMethod; request.ServerCertificateValidationCallback += ValidateCertificate; if (!context.Request.IsWebSocketRequest) { SetRequestHeaders(request, context.Request.Headers, localBaseUrl, remoteBaseUrl); } // Add RTVS headers request.Headers.Add(CustomHttpHeaders.RTVSRequestedURL, GetRemoteUrl(context.Request.Url, remoteBaseUrl)); if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length > 0) { using (Stream reqStream = await request.GetRequestStreamAsync()) { await context.Request.InputStream.CopyAndFlushAsync(reqStream, null, ct); } } HttpWebResponse response = null; try { response = (HttpWebResponse)await request.GetResponseAsync(); if (response != null) { if (context.Request.IsWebSocketRequest && response.StatusCode == HttpStatusCode.SwitchingProtocols) { Stream respStream = response.GetResponseStream(); string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol]; var remoteWebSocket = CommonWebSocket.CreateClientWebSocket(respStream, subProtocol, TimeSpan.FromMinutes(10), receiveBufferSize: 65335, useZeroMask: true); var websocketContext = await context.AcceptWebSocketAsync(subProtocol, receiveBufferSize: 65335, keepAliveInterval: TimeSpan.FromMinutes(10)); await WebSocketHelper.SendReceiveAsync(websocketContext.WebSocket, remoteWebSocket, ct); } else { context.Response.StatusCode = (int)response.StatusCode; SetResponseHeaders(response, context.Response, localBaseUrl, remoteBaseUrl); using (Stream respStream = response.GetResponseStream()) using (Stream outStream = context.Response.OutputStream) { await respStream.CopyAndFlushAsync(outStream, null, ct); } response.Close(); } } } catch (WebException wex) when (wex.Status == WebExceptionStatus.ProtocolError) { response = wex.Response as HttpWebResponse; } finally { response?.Close(); } }
public async Task <IWebSocketContext> AcceptWebSocketAsync( IEnumerable <string> requestedProtocols, string acceptedProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, CancellationToken cancellationToken) { var context = await _context.AcceptWebSocketAsync( acceptedProtocol, receiveBufferSize, keepAliveInterval) .ConfigureAwait(false); return(new WebSocketContext(this, context.SecWebSocketVersion, requestedProtocols, acceptedProtocol, new SystemWebSocket(context.WebSocket), cancellationToken)); }
private async void ProcessRequest(HttpListenerContext listenerContext) { WebSocketContext webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null); using (WebSocket webSocket = webSocketContext.WebSocket) { Random rand = new Random(1); while (webSocket.State == WebSocketState.Open) { string randomValue = rand.Next(1, 5000).ToString(); ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(randomValue)); await webSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None); await Task.Delay(new TimeSpan(0, 0, 1)); } } }
public async void Execute(HttpListenerContext context, EventSocketExecuteResult callback){ WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null); _ws = webSocketContext.WebSocket; for (int i = 0; i != 10; ++i) { // await Task.Delay(20); var time = DateTime.Now.ToLongTimeString(); var buffer = Encoding.UTF8.GetBytes(time); var segment = new ArraySegment<byte>(buffer); await _ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); } if (callback!=null) { callback (true); } // await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None); }
private async void StartAccepting(HttpListenerContext context) { do // TODO: add the appropriate try/catch here, utilize User { try { var socketContext = await context.AcceptWebSocketAsync(null); if (socketContext != null && !_disposed) { var child = new WebSocketTransportSource(socketContext.WebSocket); child.Received += OnChildReceived; _cache[socketContext.WebSocket] = child; } } catch (IndexOutOfRangeException) { // no idea what is causing this break; } } while (_listener.IsListening && !_disposed); }
async Task<int> CreateTransportAsync(HttpListenerContext context) { X509Certificate2 clientCertificate = null; if (this.listener.sslSettings != null && this.listener.sslSettings.ClientCertificateRequired) { clientCertificate = await context.Request.GetClientCertificateAsync(); ; if (clientCertificate == null) { return 403; } if (this.listener.sslSettings.RemoteCertificateValidationCallback != null) { SslPolicyErrors sslError = SslPolicyErrors.None; X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = this.listener.sslSettings.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck; chain.Build(clientCertificate); if (chain.ChainStatus.Length > 0) { sslError = SslPolicyErrors.RemoteCertificateChainErrors; } bool success = this.listener.sslSettings.RemoteCertificateValidationCallback( this, clientCertificate, chain, sslError); if (!success) { return 403; } } else if (context.Request.ClientCertificateError != 0) { return 403; } } IPrincipal principal = context.User; if (principal == null && clientCertificate != null) { principal = new GenericPrincipal(new X509Identity(clientCertificate), new string[0]); } var wsContext = await context.AcceptWebSocketAsync(WebSocketTransport.WebSocketSubProtocol); var wsTransport = new ListenerWebSocketTransport(wsContext.WebSocket, principal); await this.listener.HandleTransportAsync(wsTransport); return 0; }
private async Task<bool> ProcessConnectionAsync( CancellationToken cancellationToken, HttpListenerContext httpContext) { Logger.Debug("ProcessConnectionAsync"); WebSocketContext webSocketContext = null; try { webSocketContext = await httpContext.AcceptWebSocketAsync(null); } catch (Exception ex) { Logger.Error(ex, "AcceptWebSocketAsync"); // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500. httpContext.Response.StatusCode = 500; httpContext.Response.Close(); return false; } WebSocket webSocket = webSocketContext.WebSocket; MemoryStream ms = new MemoryStream(); try { IWebSocketConnectionHandler handler = this.createConnectionHandler(); byte[] receiveBuffer = null; // While the WebSocket connection remains open run a simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { try { if (receiveBuffer == null) { receiveBuffer = new byte[MaxBufferSize]; } WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellationToken); if (receiveResult.MessageType == WebSocketMessageType.Close) { Logger.Debug("ProcessConnectionAsync: closing websocket"); await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken); continue; } if (receiveResult.EndOfMessage) { await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken); receiveBuffer = ms.ToArray(); ms.Dispose(); ms = new MemoryStream(); } else { await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken); continue; } byte[] wsresponse = null; try { // dispatch to App provided function with requested payload wsresponse = await handler.ProcessWsMessageAsync(receiveBuffer, cancellationToken); } catch (Exception ex) { // catch any error in the appAction and notify the client wsresponse = await new ProtobufWsSerializer().SerializeAsync( new WsResponseMessage { Result = WsResult.Error, Value = Encoding.UTF8.GetBytes(ex.Message) }); } // Send Result back to client await webSocket.SendAsync( new ArraySegment<byte>(wsresponse), WebSocketMessageType.Binary, true, cancellationToken); } catch (WebSocketException ex) { Logger.Error(ex, "ProcessConnectionAsync: WebSocketException={0}", webSocket.State); } } return true; } catch (Exception ex) { Logger.Error(ex, "ProcessConnectionAsync"); throw; } }
/// <summary> /// Processes the web socket request. /// </summary> /// <param name="ctx">The CTX.</param> /// <returns>Task.</returns> private async Task ProcessWebSocketRequest(HttpListenerContext ctx) { #if !__MonoCS__ try { var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false); if (WebSocketHandler != null) { WebSocketHandler(new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() }); } } catch (Exception ex) { _logger.ErrorException("AcceptWebSocketAsync error", ex); ctx.Response.StatusCode = 500; ctx.Response.Close(); } #endif }
private static async void HandleWebSocketRequest(HttpListenerContext hc) { HttpListenerWebSocketContext connectionCtx; try { connectionCtx = await hc.AcceptWebSocketAsync(null); var webSocketInfo = new WebSocketInfo(connectionCtx.WebSocket); _sockets[webSocketInfo.Socket] = webSocketInfo; CommandListener(webSocketInfo); } catch (Exception ex) { Trace.WriteLine(nameof(MaintFace) + " Error: " + nameof(HandleWebSocketRequest) + ": " + ex.Message); return; } }
async Task HandleListenerContextAsync(HttpListenerContext context) { WebSocket webSocket = null; try { var wsContext = await context.AcceptWebSocketAsync(WebSocketTransport.WebSocketSubProtocol); var wsTransport = new WebSocketTransport(wsContext.WebSocket); await this.listener.HandleTransportAsync(wsTransport); } catch(Exception exception) { Trace.WriteLine(TraceLevel.Error, exception.ToString()); if (webSocket != null) { webSocket.Abort(); } } }
private async void ProcessRequest(HttpListenerContext httpListenerContext) { WebSocketContext webSocketContext = null; try { webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null); string ipAddress = httpListenerContext.Request.RemoteEndPoint.Address.ToString(); Console.WriteLine(String.Format("Connected: IPAddress {0}", ipAddress)); if (onConnect != null && httpListenerContext.Request.Headers.AllKeys.Contains("Sec-WebSocket-Key")) onConnect(httpListenerContext.Request.Headers["Sec-WebSocket-Key"]); } catch (Exception ex) { httpListenerContext.Response.StatusCode = 500; httpListenerContext.Response.Close(); if (onError != null) onError(String.Empty, ex); Console.WriteLine(String.Format("Exception: {0}", ex)); return; } WebSocket webSocket = webSocketContext.WebSocket; String requestKey = httpListenerContext.Request.Headers["Sec-WebSocket-Key"]; webSocketDictionary.Add(requestKey, webSocket); try { byte[] receiveBuffer = new byte[1024]; while(webSocket.State == WebSocketState.Open) { WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), System.Threading.CancellationToken.None); if (receiveResult.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", System.Threading.CancellationToken.None); webSocketDictionary.Remove(requestKey); } else { string message = Util.GetString(receiveBuffer, receiveResult.Count); if (onMessage != null) onMessage(requestKey, message); await webSocketDictionary.SendBroadcastMessage(message); receiveBuffer = new byte[1024]; } } } catch (Exception ex) { if (onError != null) onError(requestKey, ex); Console.WriteLine(String.Format("Exception: {0}", ex)); } finally { if (webSocket != null) webSocket.Dispose(); } }
/// <summary> /// Try to establish a web socket context from the specified HTTP request context. /// </summary> /// <param name="listenerContext"> /// HTTP listener context. /// </param> /// <returns> /// A web socket context if communications channel was successfully established. /// Null if web socket channel could not be established. /// </returns> /// <remarks> /// If <paramref name="listenerContext"/> does not represent a web socket request, or if /// web socket channel could not be established, an appropriate status code will be /// returned via <paramref name="listenerContext"/>'s Response property, and the return /// value will be null. /// </remarks> protected static async Task<WebSocketContext> HandleWebSocketRequestAsync(HttpListenerContext listenerContext) { if (!listenerContext.Request.IsWebSocketRequest) { listenerContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; listenerContext.Response.Close(); return null; } try { return await listenerContext.AcceptWebSocketAsync(null); } catch (WebSocketException) { listenerContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; listenerContext.Response.Close(); return null; } }
/// <summary> /// WebSocket接続毎の処理 /// </summary> /// <param name="context"></param> async void ProcessRequest(HttpListenerContext context) { Console.WriteLine("{0}:New Session:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString()); /// WebSocketの接続完了を待機してWebSocketオブジェクトを取得する var ws = (await (context.AcceptWebSocketAsync(null))).WebSocket; /// 新規クライアントを追加 _clients.Add(ws); /// WebSocketの送受信ループ while (ws.State == WebSocketState.Open) { try { var buff = new ArraySegment<byte>(new byte[1024]); /// 受信待機 var ret = await ws.ReceiveAsync(buff, CancellationToken.None); /// テキスト if (ret.MessageType == WebSocketMessageType.Text) { Console.WriteLine("{0}:String Received:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString()); string msgjson = Encoding.UTF8.GetString(buff.Take(ret.Count).ToArray()); Console.WriteLine("Message={0}", msgjson); Message msg = MessageParser.Parse(msgjson); if (msg.GetType() == typeof(JoinRoom)) { HashSet<WebSocket> room = _rooms[ws.GetHashCode().ToString()]; room.Add(ws); _rooms[ws.GetHashCode().ToString()] = room; foreach (KeyValuePair<string, HashSet<WebSocket>> val in _rooms) { if (val.Key == ws.GetHashCode().ToString()) continue; else { val.Value.Contains(ws); } } } /// 各クライアントへ配信 Parallel.ForEach(_clients, p => p.SendAsync(new ArraySegment<byte>(buff.Take(ret.Count).ToArray()), WebSocketMessageType.Text, true, CancellationToken.None)); } else if (ret.MessageType == WebSocketMessageType.Close) { Console.WriteLine("{0}:Session Close:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString()); break; } } catch { /// 例外 クライアントが異常終了しやがった Console.WriteLine("{0}:Session Abort:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString()); break; } } /// クライアントを除外する _clients.Remove(ws); ws.Dispose(); }
//### Accepting WebSocket connections // Calling `AcceptWebSocketAsync` on the `HttpListenerContext` will accept the WebSocket connection, sending the required 101 response to the client // and return an instance of `WebSocketContext`. This class captures relevant information available at the time of the request and is a read-only // type - you cannot perform any actual IO operations such as sending or receiving using the `WebSocketContext`. These operations can be // performed by accessing the `System.Net.WebSocket` instance via the `WebSocketContext.WebSocket` property. private async void ProcessRequest(HttpListenerContext listenerContext) { WebSocketContext webSocketContext = null; try { // When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol // was requested. webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null); Interlocked.Increment(ref count); Console.WriteLine("Processed: {0}", count); } catch(Exception e) { // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500. listenerContext.Response.StatusCode = 500; listenerContext.Response.Close(); Console.WriteLine("Exception: {0}", e); return; } WebSocket webSocket = webSocketContext.WebSocket; try { //### Receiving // Define a receive buffer to hold data received on the WebSocket connection. The buffer will be reused as we only need to hold on to the data // long enough to send it back to the sender. byte[] receiveBuffer = new byte[1024]; // While the WebSocket connection remains open run a simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // The first step is to begin a receive operation on the WebSocket. `ReceiveAsync` takes two parameters: // // * An `ArraySegment` to write the received data to. // * A cancellation token. In this example we are not using any timeouts so we use `CancellationToken.None`. // // `ReceiveAsync` returns a `Task<WebSocketReceiveResult>`. The `WebSocketReceiveResult` provides information on the receive operation that was just // completed, such as: // // * `WebSocketReceiveResult.MessageType` - What type of data was received and written to the provided buffer. Was it binary, utf8, or a close message? // * `WebSocketReceiveResult.Count` - How many bytes were read? // * `WebSocketReceiveResult.EndOfMessage` - Have we finished reading the data for this message or is there more coming? WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); // The WebSocket protocol defines a close handshake that allows a party to send a close frame when they wish to gracefully shut down the connection. // The party on the other end can complete the close handshake by sending back a close frame. // // If we received a close frame then lets participate in the handshake by sending a close frame back. This is achieved by calling `CloseAsync`. // `CloseAsync` will also terminate the underlying TCP connection once the close handshake is complete. // // The WebSocket protocol defines different status codes that can be sent as part of a close frame and also allows a close message to be sent. // If we are just responding to the client's request to close we can just use `WebSocketCloseStatus.NormalClosure` and omit the close message. if (receiveResult.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } // This echo server can't handle text frames so if we receive any we close the connection with an appropriate status code and message. else if (receiveResult.MessageType == WebSocketMessageType.Text) { await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept text frame", CancellationToken.None); } // Otherwise we must have received binary data. Send it back by calling `SendAsync`. Note the use of the `EndOfMessage` flag on the receive result. This // means that if this echo server is sent one continuous stream of binary data (with EndOfMessage always false) it will just stream back the same thing. // If binary messages are received then the same binary messages are sent back. else { await webSocket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None); } // The echo operation is complete. The loop will resume and `ReceiveAsync` is called again to wait for the next data frame. } } catch(Exception e) { // Just log any exceptions to the console. Pretty much any exception that occurs when calling `SendAsync`/`ReceiveAsync`/`CloseAsync` is unrecoverable in that it will abort the connection and leave the `WebSocket` instance in an unusable state. Console.WriteLine("Exception: {0}", e); } finally { // Clean up by disposing the WebSocket once it is closed/aborted. if (webSocket != null) webSocket.Dispose(); } }
private async Task<WebSocket> Handshake(HttpListenerContext ctx) { WebSocketContext webSocketContext = null; try { // When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol // was requested. webSocketContext = await ctx.AcceptWebSocketAsync(subProtocol: null); LogFacade.Instance.LogInfo("Accepted web socket connection"); } catch (Exception e) { // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500. ctx.Response.StatusCode = 500; ctx.Response.Close(); } return webSocketContext.IsNull() ? null : webSocketContext.WebSocket; }