Python,BaseHTTPRequestHandler:如何从套接字读取文件上的可用内容?
我正在使用 Python 的 BaseHTTPRequestHandler 类来构建 Web 服务器。我想为 WebSocket 添加端点。这意味着我需要读取处理程序的 rfile 中可用的任何内容,以便我可以在接收消息时一一处理它们(而不是必须读取 while 输入)。
我尝试使用不同的“读取”组合(例如,使用大缓冲区,认为如果可用数据较少,它会以较少数据提前返回;没有参数,但它只是意味着读取直到 EOF),但不能不能让它发挥作用。
我能想到两种解决方案:
调用read(1):逐个读取字节。我不想这样做,因为我不确定缓冲语义是什么(例如,我不希望每个字节读取一个系统调用)。
要暂时使文件非阻塞,然后尝试读取一块数据,然后使其阻塞,然后尝试读取 1 个字节。这看起来相当混乱。我能想到的另一个选择是仅使用非阻塞套接字,但这似乎不适用于我当前的线程框架。
关于如何读取以返回可用数据的任何想法?
I'm using Python's BaseHTTPRequestHandler class to build a web server. I want to add an endpoint for WebSockets. This means that I need to read whatever is available from the handler's rfile, so that I can process messages one by one, as I'm receiving them (instead of having to read the while input).
I tried using different combinations of 'read' (eg. with a big buffer, thinking that it'd return early with less data if less data was available; with no parameter, but then it just means to read until EOF) but couldn't get this to work.
I can think of two solutions:
To call read(1): to read bytes one by one. I'd rather not do this, as I'm not sure what the buffering semantics are (eg. I wouldn't want a syscall per byte read).
To temporally make the file non-blocking, then attempt a read for a chunk of data, then make it blocking, then attempt a read for 1 byte. This seems rather messy. Another option I can think of is to just use non-blocking sockets, but this wouldn't seem to work so well with my current threaded framework.
Any ideas of how to get read to return whatever data is available?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WebSocket 不是 HTTP,因此您无法真正使用 HTTP 请求处理程序来处理它们。
但是,将 BaseHTTPRequestHandler 与 HTTP 结合使用时,您通常只会读取您期望的确切数据量(例如,按照 Content-length 标头中指定的数据量)。
WebSockets aren't HTTP, so you can't really handle them with an HTTP request handler.
However, using BaseHTTPRequestHandler with HTTP, you would normally be reading only the exact amount of data you expect (for instance, as specified in the Content-length header.)