python:调用socket.recvfrom()两次
我正在编写两个 python 脚本,使用 python sockets 通过 UDP 进行通信。这是代码的相关部分,
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
s.setblocking(True) #I want it to be blocking
#(...)
(msg, addr) = sock.recvfrom(4)
#(...)
(msg2, addr2) = sock.recvfrom(2)
我希望接收被阻塞,并且在读取第一个 4 字节部分之前我不知道整个消息的大小。上面的代码在 sock.recvrfom(2)
部分被阻止,而修改后,用一个 sock.recvfrom
而不是两个工作正常:
(msg, addr) = sock.recvfrom(6) #works ok, but isn't enough for my needs
知道如何方便地阅读传入的数据分为两部分,或者为什么代码不能按预期工作?
I am writing two python scripts to communicate over UDP using python sockets. Here's the related part of code
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
s.setblocking(True) #I want it to be blocking
#(...)
(msg, addr) = sock.recvfrom(4)
#(...)
(msg2, addr2) = sock.recvfrom(2)
I want the receiving to be blocking and I don't know the size of the whole message before I read the first 4-byte part. The above code becomes blocked on the sock.recvrfom(2)
part, whereas modified, with one sock.recvfrom
instead of two works alright:
(msg, addr) = sock.recvfrom(6) #works ok, but isn't enough for my needs
Any idea how I can conveniently read the incoming data in two parts or why the code doesn't work as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
socket.recvfrom(size)
将(对于 UDP 套接字)读取一个数据包,最多size
字节。多余的数据将被丢弃。如果你想接收整个数据包,你必须传递一个更大的 bufsize,然后以位为单位处理数据包(而不是尝试以位为单位接收它)。如果你想要一个更方便、更稳定的网络 I/O 接口,考虑一下Twisted。
socket.recvfrom(size)
will (for UDP sockets) read one packet, up tosize
bytes. The excess data is discarded. If you want to receive the whole packet, you have to pass a larger bufsize, then process the packet in bits (instead of trying to receive it in bits.)If you want a more convenient, less fickle interface to network I/O, consider Twisted.
从 UDP 套接字读取整个数据报出队。
Read from UDP socket dequeues the whole datagram.
UDP 是一种基于消息的协议。
recvfrom
将读取最初发送的整个消息,但如果缓冲区不够大,则会抛出异常:所以我不确定为什么你如果最初发送的是 6 字节消息,则会挂在第二个
recvfrom
上。您应该在第一个recvfrom
上抛出异常。也许发布一个实际工作的客户端和服务器程序的最小示例。UDP is a message-based protocol.
recvfrom
will read the entire message that was originally sent, but if the buffer isn't big enough, it will throw an exception:So I am not sure why you would hang on the 2nd
recvfrom
if a 6-byte message was originally sent. You should throw an exception on the firstrecvfrom
. Perhaps post an actual working, minimal example of the client and the server program.