Bun*_*bit 3 python socketserver
我正在阅读 python socketserver 的文档示例我正在阅读https://docs.python.org/2/library/socketserver.html
为什么在handle方法中的line中将大小指定为1024 self.request.recv(1024)。如果客户端发送的数据超过1024字节会发生什么?是否有一个循环读取 1024 字节直到套接字为空更好?我在这里复制了这个例子:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip() # why only 1024 bytes ?
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
从套接字读取数据时,总是需要进行循环。
原因是,即使源通过网络发送了 300 字节,数据也可能作为 200 字节和 100 字节的两个单独的块到达接收器。
因此,当您指定缓冲区大小时,recv仅表示您愿意处理的最大数量,但实际返回的数据量可能会更小。
无法在 Python 级别实现“读取直到消息末尾”,因为send/recv函数只是 TCP 套接字接口的包装器,并且这是一个流接口,没有消息边界(因此无法知道如果已从源收到“所有”数据)。
这也意味着在许多情况下,如果您需要使用消息进行通信,则需要添加自己的边界(或者您需要使用更高级别的基于消息的网络传输接口,例如0MQ)
请注意,“阻塞模式”(从套接字读取时)仅定义操作系统的网络层尚未接收到数据时的行为:在这种情况下,当阻塞时,程序将等待一大块数据;如果是非阻塞的 - 它将立即返回而无需等待。如果计算机已接收到任何数据,则recv即使传递的缓冲区大小更大,调用也会立即返回 - 与阻塞/非阻塞设置无关。
阻塞模式并不意味着recv调用将等待缓冲区被填满。
注意:Python 文档确实对 的行为产生了误导recv,希望很快就能得到修复。
| 归档时间: |
|
| 查看次数: |
5316 次 |
| 最近记录: |