.net 核心 3.1 工人服务

.net core 3.1 Worker Service

我正在尝试创建一个 TCP 侦听器作为辅助服务。任何如何设法实现客户端请求和服务器响应的流程。但是,当我尝试浏览应用程序调试器的 Url 时,浏览器会点击操作方法并将响应写入流中,但无法 return 来自工作服务主线程的任何响应,即 ExecuteAsync 方法.

在这方面的任何帮助都会真正帮助我完成这项任务。

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {




        while (!stoppingToken.IsCancellationRequested)
        {
            Task.Run(() => _serverStatus = _tcpHandler.StartServer().Result).Wait();

            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now
                + Environment.NewLine
                + String.Format("Server Started with status : {0}", _serverStatus)
                + Environment.NewLine
                + String.Format("Client Message : {0}", _tcpHandler.GetServerResponse())
                + Environment.NewLine
                + String.Format("Number of Requests recieved : {0}", _tcpHandler.GetRequestCounter()));


            //  _logger.LogInformation("Server running at: {0}",  _tcpHandler.StartServer().Result);


          





            await Task.Delay(1000, stoppingToken);
        }
    }



       public async Task<string> StartServer()
    {
        string serverResponse = String.Empty;
        try
        {

            await Task.Delay(1000);




            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");
                serverResponse = "Status - Active";
                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                _tcpClient = _tcpListener.AcceptTcpClientAsync().Result;
                Console.WriteLine("Connected!");

                Console.WriteLine(Environment.NewLine + "Waiting for Requests ...");

                Thread t = new Thread(() => {

                    serverResponse = RequestHandler(_tcpClient).Result;

                });

                t.Start();








                return serverResponse;


            }


        }

        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
            return "Status - Inactive";
        }




    }

    public async Task<string> RequestHandler(object client)
    {
        string response = String.Empty;
        try
        {
            // Set the TcpListener on port 13000.


            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            // while (true)
            //{
            Console.Write("Waiting for a connection... ");

            // Perform a blocking call to accept requests.
            // You could also use server.AcceptSocket() here.
            TcpClient tcpClient = (TcpClient)client;
            Console.WriteLine("Connected!");

            data = null;

            // Get a stream object for reading and writing
            using (NetworkStream stream = tcpClient.GetStream())
            {

                int i;
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    _requestCounter++;
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    _requestedMessage = data;
                    Console.WriteLine("Message Received by Server: {0}", data);

                    // Process the data sent by the client.
                    data = "Hey ! Client ..." + data.ToUpper();


                    string xml = Environment.NewLine + "<Messages>"
                    + Environment.NewLine + "<Message>"
                    + Environment.NewLine + "<Date>" + DateTime.Now.ToString() + "</Date>"
                    + Environment.NewLine + "<Text>" + data + "</Text>"
                    + Environment.NewLine + "<status>" + "accepted" + "</status>"
                    + Environment.NewLine + "<statuscode>" + "1" + "</statuscode>"
                    + Environment.NewLine + "</Message>"
                    + Environment.NewLine + "</Messages>";




                    // Send back a response.
                    byte[] httpHeaders = System.Text.Encoding.ASCII.GetBytes("HTTP/1.1 200 OK");
                    byte[] httpContentType = System.Text.Encoding.ASCII.GetBytes("Content-Type: text/xml");
                    byte[] httpContentLength = System.Text.Encoding.ASCII.GetBytes("Content - Length: " + xml.Length);
                    byte[] newLine = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine);
                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(xml);


                    stream.Write(httpHeaders, 0, httpHeaders.Length);
                    stream.Write(httpContentType, 0, httpContentType.Length);
                    stream.Write(httpContentLength, 0, httpContentLength.Length);
                    stream.Write(newLine);
                    stream.Write(msg, 0, msg.Length);



                    response = xml;



                    Console.WriteLine("Reply sent from Server: {0}", data);
                }


                stream.Close();
            }


            // Loop to receive all the data sent by the client.


            // Shutdown and end connection

            tcpClient.Close();

            //}
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }


        return response;



    }

找到了在浏览器中从 tcp 后台服务获取 xml 响应的解决方案,而不是使用 NetworkStream StremReader 将完成处理传递的参数的工作,而 StreamWriter 会将响应写回客户端。