简体   繁体   English

Python,BaseHTTPRequestHandler:如何从套接字读取文件上可用的内容?

[英]Python, BaseHTTPRequestHandler: how to read what's available on file from socket?

I'm using Python's BaseHTTPRequestHandler class to build a web server. 我正在使用Python的BaseHTTPRequestHandler类来构建Web服务器。 I want to add an endpoint for WebSockets. 我想为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). 这意味着我需要读取处理程序的rfile中可用的所有内容,以便在接收消息时可以逐个处理消息(而不是必须读取while输入)。

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. 我尝试使用“读取”的不同组合(例如,使用大缓冲区,以为如果可用的数据较少,它将以较少的数据返回较早;没有参数,但这仅意味着读取直到EOF),但是无法不要让它工作。

I can think of two solutions: 我可以想到两种解决方案:

  • To call read(1): to read bytes one by one. 调用read(1):一次读取字节。 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. 要暂时使文件成为非阻塞文件,然后尝试读取大块数据,然后使其阻塞,然后尝试读取1个字节。 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? 关于如何读取以返回可用数据的任何想法?

WebSockets aren't HTTP, so you can't really handle them with an HTTP request handler. WebSocket不是HTTP,因此您不能真正使用HTTP请求处理程序来处理它们。

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.) 但是,将BaseHTTPRequestHandler与HTTP结合使用,通常只会读取所需的确切数据量(例如,如Content-length标头中所指定)。

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

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