简体   繁体   English

套接字:读取UDP数据包

[英]Socket: Reading UDP Packet

I've been searching about this question, but i couldn't understand the question since it was not really general, I wouldn't find the solution to read UDP packets that contain UTF-8 text for example. 我一直在搜索这个问题,但我无法理解这个问题,因为它不是一般的,我不会找到解决方案来读取包含UTF-8文本的UDP数据包。

So i make a socket, that makes a UDP packet that contains UTF-8 text, and i send it like this: 所以我创建一个套接字,它创建一个包含UTF-8文本的UDP数据包,我发送它像这样:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 80
MESSAGE = "Hello, World!"

sock = socket.socket(socket.AF_INET, 
             socket.SOCK_DGRAM) 
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

Lets define this as sender.py . 让我们将其定义为sender.py

Now i want to make a reciever.py script that will be executed after sender.py . 现在我想打一个reciever.py会后执行脚本sender.py

How can i make that? 我该怎么做? I've heard of Data, addr = udp.recvfrom(1024) but i'm not entirely sure how it works/how to use it. 我听说过Data, addr = udp.recvfrom(1024)但我不完全确定它是如何工作的/如何使用它。

So whenever i execute them together, Reciever.py can print UTF-8 text of UDP packet sent. 因此,每当我一起执行它们时, Reciever.py都可以打印发送的UDP数据包的UTF-8文本。

You'll want the receiver to do several things: 你希望接收器做几件事:

  1. Create a socket sock using socket.socket . 使用socket.socket创建套接字sock
  2. Bind to the socket using sock.bind . 使用sock.bind绑定到套接字。
  3. In an infinite loop, execute: data, addr = sock.recvfrom(1024) . 在无限循环中,执行: data, addr = sock.recvfrom(1024)
  4. Now the received data is available for your use and you can handle it as you wish. 现在收到的数据可供您使用,您可以根据需要进行处理。

Note that the receiver will sleep, waiting until a message appears in the socket it has bound to. 请注意,接收器将休眠,等待它绑定到的套接字中出现消息。 After handling the data, the loop will execute once again and the receiver will go back to sleep. 处理完数据后,循环将再次执行,接收器将返回休眠状态。

1024 corresponds to the maximum size message you can receive (around 1024 characters, since 1 character = 1 byte. If you want to be able to receive larger messages, make this value larger. 1024对应于您可以接收的最大大小消息(大约1024字符,因为1字符= 1个字节。如果您希望能够接收更大的消息,请将此值放大。

See https://wiki.python.org/moin/UdpCommunication for a detailed code example. 有关详细的代码示例,请参阅https://wiki.python.org/moin/UdpCommunication

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

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