Python:普通套接字和HTTP连接的异步发送/接收

0 投票
1 回答
789 浏览
提问于 2025-04-16 16:06

我有一个任务,需要在前端接收消息(普通字符串),然后进行一些处理,把这些消息转换成需要发送到后端服务器的HTTP请求。简单来说,这里有两个端点——前端是一个普通的BSD套接字,后端是一个urllib.HTTPconnection。响应的方向是相反的。不过,这并不是一个请求-响应的场景。我可能会遇到完全无序的情况,比如req1->req2->resp2->req4->req3->resp3->resp1这样的异步场景。所以我不能简单地这样做:

msg = socketFrontEnd.recv()
... process msg and make 'Request' 
resp, content = httpBackEnd.request("http://example.org", "PUT", body=Request)   
... process resp and make 'Response'
socketFrontEnd.send(Response)

我需要一种更像轮询机制的东西:

While(True):
   readysockets = select(SocketFrontEnd, httpBackEnd)

   if readysockets has SocketFrontEnd:
       msg = socketFrontEnd.recv()
       process and send request to httpBackEnd(...)

   if readysockets has httpBackEnd:
       resp = httpBackEnd(...)
       process and send response to socketFrontEnd()

不过,尽我所知,我不能把HTTP连接放在某种选择语句中。即使可以,那我该怎么单独从httpconnection发送和接收数据呢(而不是使用单一的“http.request(..)”命令)?

如果我在httpconnection上发送一些ajax请求,当我在socketFrontEnd上被阻塞时,那个ajax请求的回调会被执行吗?也就是说,我们能不能做类似这样的事情:

while(True):
    msg = socketFrontEnd.recv() <-- blocked
    ... process and make 'Request'
    ajax('callback_function', Request, 'http://backendserver.com')


Callback_function(resp):
    ... process and make Response
    socketFrontEnd.send(Response)

1 个回答

1

Python的asyncore模块是不是不太适合你的问题?或者像Twisted这样的框架呢?

撰写回答