/// <summary> /// Handle HTTP request. /// </summary> /// <param name="result"></param> private void HttpRequest(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); OnHttpRequest?.Invoke(context); } catch { // TODO: Can't handle request. } }
private static void mk_http_request(IntPtr mk_parser, IntPtr mk_http_response_invoker, ref int consumed, IntPtr mk_sock_info) { if (OnHttpRequest == null) { return; } consumed = 1; var httpBody = OnHttpRequest.Invoke(new HttpRequest(mk_parser, mk_sock_info)); if (httpBody == null) { consumed = 0; return; } httpBody.GetHttpHeader(); PInvoke.ZLMediaKitMethod.mk_http_response_invoker_do(mk_http_response_invoker, $"{(int)httpBody.HttpStatusCode} {httpBody.HttpStatusCode}", ref httpBody.headerIntptr, httpBody.GetHttpBody()); }
// The third parameter makes it possible to easily handle the case where a http connection turns into a websocket by simply handing it back to the caller. public WebSocketServer(int listenerThreads, int connectionMS, string prefixURL, OnHttpRequest httpRequest, Action <string, int> logger, Action <RGWebSocket> websocketConnection, Action <RGWebSocket, string> onReceiveMsgTextCb, Action <RGWebSocket, byte[]> onReceiveMsgBinaryCb, Action <RGWebSocket> onDisconnect) { _listenerThreads = listenerThreads; _connectionMS = connectionMS; _prefixURL = prefixURL; _httpRequestCallback = httpRequest; _logger = logger; _websocketConnection = websocketConnection; _onReceiveMsgText = onReceiveMsgTextCb; _onReceiveMsgBinary = onReceiveMsgBinaryCb; _onDisconnect = onDisconnect; _listenerRunning = null; _listenerUpdateTask = null; _listener = new HttpListener(); _listener.Prefixes.Add(prefixURL); _websockets = new ConcurrentDictionary <int, RGWebSocket>(); _disconnected = new ConcurrentDictionary <int, RGWebSocket>(); }
// httpRequest callback allows you to handle ordinary non-websocket HTTP requests however you want, even at the same url public WebSocketServer(int listenerThreads, int connectionMS, int idleSeconds, string prefixURL, OnHttpRequest httpRequest, IConnectionManager connectionManager, Action <string, int> logger) { if (logger == null) { throw new Exception("Logger may not be null."); } if (connectionManager == null) { throw new Exception("ConnectionManager may not be null."); } _listenerThreads = listenerThreads; _idleSeconds = TimeSpan.FromSeconds(idleSeconds); // This is actually the duration between keepalive messages automatically sent by websocket library. _connectionMS = connectionMS; _prefixURL = prefixURL; _httpRequestCallback = httpRequest; _logger = logger; _connectionManager = connectionManager; _listener = new HttpListener(); _listener.Prefixes.Add(_prefixURL); _listener.TimeoutManager.IdleConnection = _idleSeconds; // idle connections are cut after this long }