尝试通过网络发送UDP时出错

时间:2020-10-07 20:57:33

标签: python udp

我正在尝试通过本地网络与具有树莓派的ETC EOS照明控制台进行通信。

这是我当前正在使用的代码:

import socket

UDP_IP = "10.1.10.149"
UDP_PORT = "0"
MESSAGE = "$ Channel 1 @ FULL #"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

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

我收到的错误是

Traceback (most recent call last):
  File "/home/pi/Desktop/eoscontrol.py", line 13, in <module>
    sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
TypeError: a bytes-like object is required, not 'str'

如何将我的字符串更改为字节以解决此错误?

我是python的新手,我敢打赌这很简单,我只是不太了解。

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要通过首先编码以字节格式发送数据。以下应该适合您

sock.sendto(bytes(MESSAGE, 'utf-8'), (UDP_IP, UDP_PORT)) #