【问题标题】:open a UDP socket on python 3.5在 python 3.5 上打开一个 UDP 套接字
【发布时间】:2016-07-23 01:57:31
【问题描述】:

我正在尝试在 python 3.5 上打开一个 udp 套接字。我在 python 2.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 : 

client_socket.sendto(数据,地址)

TypeError: a bytes-like object is required, not 'str'  

【问题讨论】:

    标签: python sockets python-3.x udp


    【解决方案1】:

    在 Python 3 中,socket 上的 sendtosendsendall 方法现在采用 bytes 对象,而不是 strs。为了为您的代码解决此问题,您需要调用 .encode() 您的字符串,例如:

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

    在定义它们时使用字节字符串文字

    outputOFF_2 = b"OFF_2"
    

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

    还请记住,recvrecvfrom 现在也将返回 bytes,因此您可能需要 .decode() 它们(同样的规则适用于 .decode.encode)。

    【讨论】:

      【解决方案2】:

      您需要使用

      对字符串进行编码
      client_socket.sendto(bytes(data, 'utf-8') , address)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 2014-04-16
        • 1970-01-01
        • 2013-06-16
        • 2013-10-25
        相关资源
        最近更新 更多