2016-04-03 23 views
1

私はpython 3.5でudpソケットを開こうとしています。私はPython 2.7でPythonコードを書いています。私はそれは私にエラーを与えるのpython 3.5に移ったときに、これは、Pythonのコードです:Python 3.5でUDPソケットを開く

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' 

答えて

0

あなたは

を使用して文字列をエンコードする必要がありますPythonの3では
client_socket.sendto(bytes(data, 'utf-8') , address) 
1

socketsendtosendsendall方法は今bytesオブジェクトを取得していないstr s。それらを定義するとき

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

それとも使用バイトの文字列リテラル:あなたのコードのためにこの問題を解決するためには、あなたが、.encode()あなたの文字列をコールするなどが必要

outputOFF_2 = b"OFF_2" 

s.encode()

、デフォルトでは、 utf8を使用して文字列( s)をエンコードします。例えば、 s.encode('ascii')のように、代替のエンコーディングを引数として指定できます。

recvrecvfromは今もbytesはそうあなたが(同じルールが.encodeとして.decodeに適用されます).decode()にそれらを必要とするかもしれないが返されますことを心に留めておいて。

関連する問題