我正在尝试编写一个程序来发送 UDP 数据包,如 https://wiki.python.org/moin/UdpCommunication代码似乎在 Python 2 中:
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
如果我在打印的内容周围加上括号,它只会将其打印在屏幕上。
我需要做什么才能完成这项工作?
最佳答案
使用 Python3x,您需要将字符串转换为原始字节。您必须将字符串编码为字节。通过网络,您需要发送字节而不是字符。没错,这适用于 Python 2x,因为在 Python 2x 中,套接字上的 socket.sendto 采用“纯”字符串而不是字节。试试这个:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
关于Python发送UDP数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743962/