简体   繁体   English

在Python中使用套接字recvfrom接收多播数据

[英]Receiving multicast data with socket recvfrom in Python

I have a multicast server sending data that must be captured by a python client. 我有一个多播服务器发送必须由python客户端捕获的数据。 The problem is that recvfrom does not receive any data or at least receive the first packet and sorta caches it. 问题是recvfrom不接收任何数据或至少接收第一个数据包并对其进行缓存。 If I use recvfrom in a loop then my data is received correctly. 如果我在循环中使用recvfrom,则可以正确接收我的数据。

My question is why I should use recvfrom in a loop to have the expected behavior? 我的问题是为什么我应该在循环中使用recvfrom来达到预期的行为?

from socket import *

s=socket(AF_INET, SOCK_DGRAM)
s.bind(('172.30.102.141',12345))
m=s.recvfrom(1024)
print m[0]

# sleep for x seconds here

m=s.recvfrom(1024)
print m[0]
# print the exact same thing as previously...

One thing is for sure, multicast is basically sending UDP packages and you have to keep listening for new packages. 可以肯定的是,多播基本上是在发送UDP程序包,您必须继续侦听新程序包。 That is true even for TCP protocol based communication. 即使基于TCP协议的通信也是如此。

When you use low level interfaces for network communication, like socket is, it's up on both sides to define application level protocol. 当您使用低级接口进行网络通信(例如socket )时,双方都在定义应用程序级协议。

That means, you define how receiving party concludes that message is complete. 这意味着,您可以定义接收方如何得出消息完整的结论。 This is because message could get split in multiple parts/packets that get through the network. 这是因为消息可能会分成通过网络的多个部分/数据包。 So receiving side has to assemble them in a proper way and then check if the message is whole. 因此,接收方必须以适当的方式组装它们,然后检查消息是否完整。 After that you push it up through the pipeline of processing messages or whatever you do in receiving side. 之后,您可以通过处理消息的管道或在接收端执行的任何操作将其向上推送。

When using UDP, receiving side doesn't know if there is any packet on its way, so it just does try to recvfrom 1024 bytes and finishes. 当使用UDP,接收方不知道是否有在途中的任何数据包,所以它只是尝试recvfrom 1024个字节和完成。 It doesn't know and should not care if there is more data on it's way. 它不知道也不应该在意途中是否有更多数据。 It's up to you to take care of that. 这取决于您自己。

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

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