Beispiel #1
0
        public static void Publish(string urlRelative, IResponse response)
        {
            if (_channel.TryGetValue(urlRelative, out BlockingCollection <KeyValuePair <TcpClient, NetworkStream> > clients) &&
                clients != null)
            {
                List <Task> tasks = new List <Task>();
                foreach (var client in clients)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        if (!client.Key.Client.Connected)
                        {
                            WebsocketServerHub.Remove(urlRelative);
                            return;
                        }
                        WebsocketServerHub.Send(client.Key, client.Value, response);
                    }));
                }

                //want to make sure sent all to client
                //Task.WhenAll(tasks).GetAwaiter().GetResult();
            }
        }
        async Task InternalStartAcceptIncommingAsync(TcpListener tcpListener)
        {
            //you may want to do with ssl
            //https://docs.microsoft.com/en-us/dotnet/api/system.net.security.sslstream?redirectedfrom=MSDN&view=netcore-3.1
            while (!_isStop)
            {
                try
                {
                    if (_isWss)
                    {
                        //https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server
                        TcpClient clientWssAccepted = await tcpListener.AcceptTcpClientAsync();

                        NetworkStream clientStream             = clientWssAccepted.GetStream();
                        HttpRequest   wss1stRequestOfHandShake = null;

                        Task twss = Task.Run(async() =>
                        {
                            while (!_isStop)
                            {
                                if (!clientWssAccepted.Client.Connected)
                                {
                                    if (wss1stRequestOfHandShake != null)
                                    {
                                        WebsocketServerHub.Remove(wss1stRequestOfHandShake.UrlRelative);
                                    }
                                    await Shutdown(clientWssAccepted.Client, wss1stRequestOfHandShake);
                                    break;
                                }

                                while (!clientStream.DataAvailable)
                                {
                                    ;
                                }
                                while (clientWssAccepted.Available < 3)
                                {
                                    ;                                     // match against "get"
                                }
                                byte[] wssReceivedBytes = new byte[clientWssAccepted.Available];
                                await clientStream.ReadAsync(wssReceivedBytes, 0, clientWssAccepted.Available);

                                var handShakeRequest = await WebsocketServerHub.DoHandShaking(clientWssAccepted, clientStream, wssReceivedBytes);

                                if (handShakeRequest != null)
                                {
                                    wss1stRequestOfHandShake = handShakeRequest;
                                }

                                await WebsocketServerHub.ReceiveAndReplyClientMessage(clientWssAccepted, clientStream, wssReceivedBytes, wss1stRequestOfHandShake);
                            }
                        });

                        continue;
                    }

                    //WebHostWorker will try accept its job
                    Socket clientSocket = await tcpListener.AcceptSocketAsync();

                    //parse request then dispatched by RoutingHandler
                    var t = Task.Run(async() =>
                    {
                        Task <HttpRequest> tRequest = ReadByteFromClientSocketAndBuildRequest(clientSocket);

                        HttpRequest request = new HttpRequest();

                        request.CreatedAt      = DateTime.Now;
                        request.RemoteEndPoint = clientSocket.RemoteEndPoint.ToString();

                        var tempRequest = await tRequest;

                        request.Body                 = tempRequest.Body;
                        request.Error                = tempRequest.Error;
                        request.Header               = tempRequest.Header;
                        request.HeadlerCollection    = tempRequest.HeadlerCollection;
                        request.HttpVersion          = tempRequest.HttpVersion;
                        request.Method               = tempRequest.Method;
                        request.QueryParamCollection = tempRequest.QueryParamCollection;
                        request.Url            = tempRequest.Url;
                        request.UrlRelative    = tempRequest.UrlRelative;
                        request.UrlQueryString = tempRequest.UrlQueryString;

                        //dispatched routing here
                        var processedResult = await RoutingHandler.Handle(request);

                        HttpResponse response = await HttpTransform.BuildHttpResponse(processedResult, request);

                        await SendResponseToClientSocket(clientSocket, request, response);

                        await Shutdown(clientSocket, request);

                        HttpLogger.Log(request);

                        Console.WriteLine($"{request.RemoteEndPoint}@{request.CreatedAt}=>{request.Method}:{request.Url}");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(JsonConvert.SerializeObject(ex));
                }
                finally
                {
                    await Task.Delay(0);
                }
            }
        }