在python 3.5上打开UDP套接字
我正在尝试在Python3.5上打开udp套接字。我在Python2.7上编写了一个python代码,它可以正常工作。当我转到python 3.5时,它给了我一个错误,这是python代码:在python 3.5上打开UDP套接字,python,sockets,python-3.x,udp,Python,Sockets,Python 3.x,Udp,我正在尝试在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
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 :
您需要使用
client_socket.sendto(bytes(data, 'utf-8') , address)
在Python 3中,
socket
上的sendto
、send
和sendall
方法现在使用字节
对象,而不是str
s。为了修复代码中的此问题,您需要调用字符串.encode()
,例如:
client_socket.sendto(outputOFF_2.encode() , address)
或在定义字节字符串文字时使用它们:
outputOFF_2 = b"OFF_2"
默认情况下,s.encode()
将使用utf8
对字符串(s
)进行编码。可选编码可以作为参数提供,例如:s.encode('ascii')
还要记住,recv
和recvfrom
现在也将返回字节
,因此您可能需要.decode()
它们(同样的规则适用于.decode
和.encode
)
outputOFF_2 = b"OFF_2"