我正在浏览一个基本套接字教程(http://www.binarytides.com/python-socket-programming-tutorial/),我遇到了一个奇怪的错误,当我向主机发送数据时出现错误
sock.sendall(message) 'str' does not support the buffer interface
所以这个教程有点过时了python的新版本,也许我使用的是过时的代码,但我希望有人可以看看并找出我遇到这个问题的原因。我的想法是,HTTP命令可能是错误的?但我做了一些研究,这似乎是正确的。谢谢你的帮助!
import socket
import sys
#error handling
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
print ("Failed to create socket." + str(e[1]) + " . Error message : " + e[1])
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()
print ("IP address of " + host + " is " + remote_ip)
#connect to remote
sock.connect((remote_ip, port))
print ("Socket Connected to " + host + "on ip " + remote_ip)
#send some data to client
message = "GET / HTTP/1.1\r\n\r\n"
try:
#set the whole string
sock.sendall(message) #THIS IS WHERE THE ERROR IS OCCURING
except socket.error:
#send Failed
print ("send failed")
sys.exit()
print ("message sent successfully ")