我正在尝试解析HTTP请求行(例如' GET / HTTP / 1.1 \ r \ n '),这很容易通过使用socket.makefile()。readline()函数(BaseHTTPRequestHandler使用它)来实现,例如:
print sock.makefile().readline()
Run Code Online (Sandbox Code Playgroud)
不幸的是,如文档所述,使用makefile()时,套接字必须处于阻塞模式(不能有超时);我该如何实现类似readline()的函数,而无需使用makefile()文件对象接口并且读取的内容不超过所需数量(因为它将丢弃我以后需要的数据),该功能是否相同?
一个非常低效的例子:
request_line = ""
while not request_line.endswith('\n'):
request_line += sock.recv(1)
print request_line
Run Code Online (Sandbox Code Playgroud)