我正在尝试编写一个程序来发送 UDP 数据包,如https://wiki.python.org/moin/UdpCommunication 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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)