我试图在python3.5上打开udp套接字。我在python2.7上编写了一个python代码,它可以工作。当我转到python 3.5时,它给了我一个错误,这是python代码:
from socket import *
import time
UDP_IP="192.168.1.26"
UDP_PORT = 6009
UDP_PORT2 = 5016
address= ('192.168.1.207' , 5454)
client_socket = socket(AF_INET , SOCK_DGRAM)
client_socket.settimeout(1)
sock = socket (AF_INET , SOCK_DGRAM)
sock.bind((UDP_IP , UDP_PORT))
sock2 = socket(AF_INET , SOCK_DGRAM)
sock2.bind((UDP_IP , UDP_PORT2))
while (1) :
data = "Temperature"
client_socket.sendto(data , address)
rec_data,addr = sock.recvfrom(2048)
temperature = float(rec_data)
print (temperature)
outputON_1 = 'ON_1'
outputOFF_1 = 'OFF_1'
seuil_T = 25.00
if (temperature < seuil_T) :
client_socket.sendto(outputOFF_1, address)
else :
client_socket.sendto(outputON_1 , address)
## sock.close()
data = "humidity"
client_socket.sendto(data , address)
rec_data , addr =sock2.recvfrom(2048)
humidity = float (rec_data)
print (humidity)
outputON_2 = "ON_2"
outputOFF_2 = "OFF_2"
seuil_H = 300
if humidity < seuil_H :
client_socket.sendto(outputOFF_2 , address)
else:
client_socket.sendto(outputON_2 , address)
This is the error that I got :
客户_插座.sendto(数据、地址)
^{pr2}$
在Python3中,}。为了修复代码中的这个问题,需要调用
socket
上的sendto
、send
和sendall
方法现在采用bytes
对象,而不是{.encode()
字符串,例如:或在定义字节字符串文本时使用字节字符串文本:
^{pr2}$默认情况下,
s.encode()
将使用utf8
对字符串(s
)进行编码。可选编码可以作为参数提供,例如:s.encode('ascii')
。在还要记住,
recv
和recvfrom
现在也将返回bytes
,因此您可能需要.decode()
它们(与.encode
相同,.decode
也将返回它们。在你需要用
相关问题 更多 >
编程相关推荐