在Python 3.5上打开一个UDP套接字

2024-10-01 07:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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}$

Tags: ipclientdataaddresssocketsockudpaf
2条回答

在Python3中,socket上的sendtosendsendall方法现在采用bytes对象,而不是{}。为了修复代码中的这个问题,需要调用.encode()字符串,例如:

client_socket.sendto(outputOFF_2.encode() , address)

在定义字节字符串文本时使用字节字符串文本:

^{pr2}$

默认情况下,s.encode()将使用utf8对字符串(s)进行编码。可选编码可以作为参数提供,例如:s.encode('ascii')。在

还要记住,recvrecvfrom现在也将返回bytes,因此您可能需要.decode()它们(与.encode相同,.decode也将返回它们。在

你需要用

client_socket.sendto(bytes(data, 'utf-8') , address)

相关问题 更多 >