2016-05-30 4 views
0

http://www.binarytides.com/python-socket-programming-tutorial/のコードを取得し、Python 3.5で動作するように変更しました。それは次のようになりますソケットコードを使用してPython 3.5.0に変更し、TypeErrorを取得すると、 'str'エラーではなくバイト型のオブジェクトが必要です

#Socket client example in python 

import socket #for sockets 
import sys #for exit 

#create an INET, STREAMing socket 
try: 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
except socket.error: 
    print ('Failed to create socket') 
    sys.exit() 

print ('Socket Created') 

host = 'www.google.com'; 
port = 80; 

try: 
    remote_ip = socket.gethostbyname(host) 

except socket.gaierror: 
    #could not resolve 
    print ('Hostname could not be resolved. Exiting') 
    sys.exit() 

#Connect to remote server 
s.connect((remote_ip , port)) 

print ('Socket Connected to ' + host + ' on ip ' + remote_ip) 

#Send some data to remote server 
message = ("GET/HTTP/1.1\r\n\r\n") 

try : 
    #Set the whole string 
    s.sendall(str(message)) 
except socket.error: 
    #Send failed 
    print ('Send failed') 
    sys.exit() 

print ('Message send successfully') 

#Now receive data 
reply = s.recv(4096) 

print (reply) 

とシェルはエラー「はTypeError:バイトのようなオブジェクトが必要である、ではない 『STR』」を与えているコードがs.sendall(STR(メッセージ)であるライン36上に)。私は学校のプロジェクトのためのソケットプログラミングに取り掛かることを試みているので、私は本当にエラーが何を意味しているのか分かりませんし、それを解決する良い例を見つけていません。

答えて

0

socket().sendallメソッドは、bytesオブジェクト(またはmemoryviewのような他のタイプの束)を意味する「バイト様オブジェクト」を想定しています。ユニコード文字列を表すstrオブジェクトをそのメソッドに渡しています。

このエラーを修正するには、メッセージをmessage.encode(<encoding>)またはbytes(message,<encoding>)でエンコードする必要があります。

関連する問題