繁体   English   中英

C# 应用程序在对 python http 服务器的 POST 请求期间挂起

[英]C# application hangs during POST request to python http server

我有一个 C# 应用程序向在 Python 中创建的简单 http 服务器发出 post 请求,但我的请求永远不会“完成”,并且不会超过发出异步 POST 请求的进度。 这是我从我的客户(C# 应用程序)打来的电话:

private void sendPost(HttpClientAdaptor client, MyDataObject myDataObject) {
   

    var payload = JsonConvert.SerializeObject(myDataObject);
    var content = new StringContent(payload, Encoding.UTF8, "application/json");

    try {
        if (client.isDisposed) {
            return;
        }

        var response = client?.PostAsync(ApiEndpoint, content); // this hangs forever

我用python编写的http服务器:

#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
from io import BytesIO


class S(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'This is POST request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())

def run(server_class=HTTPServer, handler_class=S, port=5000):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

我知道请求正在发送到我的服务器,因为我使用了一些打印语句来打印有效负载,但我的客户端似乎从未确认来自我的服务器的 200 响应。 我已经验证服务器正在运行,我没有混淆端口,并且 GET 请求通过浏览器工作。

我怀疑我的 python 服务器出了点问题,以至于它没有“完成”交易,因此我的客户没有得到响应。

顺便说一句:有没有更简单的方法来为我的客户端启动一个 http 服务器(用 C# 编写的 Windows 应用程序)? 我只需要一种返回 200 状态的方法。

您正在使用异步函数并且没有等待它。

代替

var response = client?.PostAsync(ApiEndpoint, content);

尝试

  var response = await client?.PostAsync(ApiEndpoint, content);

并更改您的方法签名

private void sendPost

private async Task sendPost

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM