【问题标题】:TcpListener parserTcpListener 解析器
【发布时间】:2022-03-07 07:17:53
【问题描述】:

我有一个简单的 TcpListener,我想解析它接收到的数据。这是我所拥有的并且它有效:

TcpListener listener = new TcpListener(localAddr, port);
var client = listener.AcceptTcpClient();
var buffer = new byte[10240];
var stream = client.GetStream();
var length = stream.Read(buffer, 0, buffer.Length);
var incomingMessage = Encoding.UTF8.GetString(buffer, 0, length);

结果

Incoming message: POST /api/v1/myapi/ HTTP/1.1
Content-Type: application/json
ApiKey: dac38055e7914b1f8ca5de1683b58322
cache-control: no-cache
Postman-Token: 50da88e4-5c89-4368-a5eb-1574eb35b24a
User-Agent: PostmanRuntime/7.6.1
Accept: */*
Host: MyDNS:13000
accept-encoding: gzip, deflate
content-length: 590
Connection: keep-alive

AmazingDataFromBody

有什么可以解析这个还是我必须自己写?

【问题讨论】:

  • .Net 提供了HttpClient,为什么不使用呢?还是 Web API?看来您正在尝试重新发明轮子。

标签: c# tcplistener


【解决方案1】:

如我所见,你想处理一个 HTTP 请求,所以:

  1. 使用HttpListener 代替TCPListener 来处理HTTP 请求和响应。链接:https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netframework-4.7.2
  2. 使用您的 URI http:localhost[:port]/api/v1/myapi/,使用主机和端口将前缀添加到 HTTPLister
  3. StartHttpListener
  4. 使用GetContext() 获取HttpListenerRequest 对象。
  5. 使用HttpListenerRequest,您可以获得标题和正文,请查看此链接:https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistenerrequest?view=netframework-4.7.2
  6. 使用GetContext() 获取HttpListenerResponse 对象。

使用https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netframework-4.7.2的样例可以看到:

    // This example requires the System and System.Net namespaces.
    public static void SimpleListenerExample(string[] prefixes)
    {
        // 1
        HttpListener listener = new HttpListener();
        // 2
        listener.Prefixes.Add("http:/localhost:8080//api/v1/myapi/");

        // 3
        listener.Start();
        Console.WriteLine("Listening...");

        //4
        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;

        //5
        HttpListenerResponse response = context.Response;

        //Building a response
        string responseString = "<HTML><BODY>My response</BODY></HTML>";
        //Take care of encoding
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

        //6
        response.ContentLength64 = buffer.Length;
        //Get the stream to wite the response body
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer,0,buffer.Length);
        // You must close the output stream.
        output.Close();
        listener.Stop();
    }

如果您不想使用HttpListener,您可以使用这些基本步骤,使用TCPListenerTCPClient,但您必须了解 HTTP 协议:

  1. 逐行阅读标题。
  2. 如果有 Body 则有效,使用 content-length 标头。
  3. 读取正文,根据content-length的大小信息。

在我的情况下,我更喜欢使用HttpListener,它允许处理 HTTP 的多个方面,例如认证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2015-03-25
    • 2016-02-24
    • 2015-12-11
    • 1970-01-01
    • 2012-09-13
    • 2012-05-21
    相关资源
    最近更新 更多