c# - 如何处理一些异步的 TcpClient 响应?

标签 c# web-services asynchronous tcp

我使用 this class for asynchronous client-server TCP network connection在我的项目中。

我最常连接到“远程服务器”并通过 TCP 连接(来自另一家我们无法更改 TCP 以外的通信方法的公司)发送和接收数据“接口(interface) Web 服务”。

这个“Interface Web Service”处理“Client Apps”请求,创建数据并通过 TCP 连接传递到“Remote server”,并将“远程服务器”的(响应)解析响应传递给“客户端应用程序”。

注意当前的 TCP 连接,通过 OnDataReceived 事件接收“Remote server”响应。 (这个事件很好,我想在接下来的步骤中使用这个事件)。

如何访问和处理这些异步响应并传递“Client Apps”请求的完整响应?

总结:

  1. Client app 发送请求到Interface service
  2. 接口(interface)服务远程服务器创建命令
  3. 远程服务器 响应来自接口(interface)服务
  4. 的命令
  5. 现在在 Interface service 中,使用 OnDataReceived 事件处理响应,我无法从 Interface service 访问它> 处理 Client App 请求。问题在这里...

查看此图片以了解我的场景:

Scenario of communications

最佳答案

请查看该类的以下完整(尚未优化)工作示例。

注意 MyHandler.ProcessRequest 方法中的 while 循环。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using System.Threading.Tasks;

namespace TestApp
{
    class Program
    {

        private static NetConnection fakeServerConnector { get; set; }

        static void Main(string[] args)
        {
            var pageHandler = new MyHandler();
            var tw = Console.Out;
            var builder = new UriBuilder();
            builder.Host = "localhost";
            builder.Port = 80;
            builder.Query = "";

            initFakeServer(8080);

            pageHandler.ProcessRequest(
                new HttpContext(
                    new HttpRequest("index.html", builder.ToString(), ""),
                    new HttpResponse(tw))
                    );

            ConsoleKey key;
            Console.WriteLine(Environment.NewLine + "Press [Enter] or [Esc] to exit!");
            do
            {
                key = Console.ReadKey().Key;
            } while (!(key == ConsoleKey.Enter || key == ConsoleKey.Escape));
        }

        private static void initFakeServer(int Port)
        {
            fakeServerConnector = new NetConnection();
            fakeServerConnector.OnDataReceived += fakeServerConnector_OnDataReceived;
            fakeServerConnector.Start(Port);

        }

        static void fakeServerConnector_OnDataReceived(object sender, NetConnection connection, byte[] e)
        {
            Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(e));
            var msg = System.Text.UTF8Encoding.UTF8.GetBytes("Fake Server says: \"Hi\"");
            connection.Send(msg);
        }
    }

    public class MyHandler : IHttpHandler
    {

        public string HostName { get; set; }
        public int Port { get; set; }
        private NetConnection clientConnector { get; set; }
        private bool isReceived;
        private byte[] responsePayload;

        public bool IsReusable
        {
            get { return false; }
        }



        public void ProcessRequest(HttpContext context)
        {            
            HostName = "localhost";
            Port = 8080;

            clientConnector = new NetConnection();
            clientConnector.OnDataReceived += OnDataReceivedHandler;
            clientConnector.Connect(HostName, Port);
            clientConnector.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Client Connector says: \"Hello World\""));
            while (!isReceived)
            {
                // do nothing; wait for isReceived to become true;
            }
            var responsePayloadText = System.Text.ASCIIEncoding.UTF8.GetString(responsePayload, 0, responsePayload.Length);
            context.Response.Write(responsePayloadText + Environment.NewLine);
        }


        public void OnDataReceivedHandler(object sender, NetConnection connection, byte[] data)
        {
            isReceived = true;
            responsePayload = data;
        }
    }    
}

关于c# - 如何处理一些异步的 TcpClient 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32206244/

相关文章:

c# - Entity Framework Core 2 - 代码优先不创建表

C# 基本类型(double、int 等)和 Struct 差异

c# - 4.5.1也是4.0和4.5的就地升级吗?

java - Soap 服务在本地工作,但在另一台服务器上引发 ClassCastException

c# - 如何从 C# web 服务生成 WSDL 文件

c++ - 池化异步对象以获得更好的性能

javascript - 为什么在 for 循环中声明的变量会更新而不是在每次迭代时重新创建?

c# - 如何在 C# 中为已在 WPF 中的 XAML 中声明的矩形着色?

iphone - 按住按钮直到 Action 在 ios 中执行

c# - 字典中存在键时出现 KeyNotFound 异常?