Python recv multicast returns 一个字节

Python recv multicast returns one byte

recv 未按预期工作。 我正在发送 10 个字节(使用 wireshark 验证)并且 recv 仅获取第一个字节并丢弃其余字节(直到下一个 sendto)。 这是多播的东西吗?我很确定我已经用单播 UDP 做了同样的事情并且没有任何问题。

这是我的示例代码:

import struct, socket, multiprocessing, time

MCAST_PORT = 62950
MCAST_GRP = '239.0.0.13'

def _Rx(self, RXsock, Queue):
   print "Receiver started"
   while True:
      # State machine goes here to parse header and recv (<msglen>) bytes.
      print "Waiting Rx char...", RXsock
      char = RXsock.recv(1)  # Blocks here after first byte ("1") ???
      print "Rx", hex(ord(char))



TXsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
TXsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

RXsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
RXsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
RXsock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
RXsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

RxQueue = multiprocessing.Queue()
receiver = multiprocessing.Process(target=_Rx, args=(None, RXsock, RxQueue))
receiver.daemon = True
receiver.start()


TXsock.sendto("09123456789", (MCAST_GRP, MCAST_PORT))
time.sleep(3)

您只得到一个字节,因为您将缓冲区大小设置为 1。

来自documentation for socket.recv

The maximum amount of data to be received at once is specified by bufsize.

尝试将 10244096 传递给 recv

来自man page for recv

If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from.

您的评论说您正在尝试一次解析 header 一个字节。您可以在接收完数据报后随时解析 header。

如果您确实需要对缓冲区进行部分读取,请尝试将 socket.MSG_PEEK 标志传递给 recv:

MSG_PEEK

This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.

但是,您仍然无法一次读取一个字节。