在python2.7中完好运行:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# 导入socket库:
import socket
# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('www.sina.com.cn', 80))
s.send('GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
# 接收数据:
buffer = []
while True:
# 每次最多接收1k字节:
d = s.recv(1024)
if d:
buffer.append(d)
else:
break
data = ''.join(buffer)
print (data)
# 关闭连接:
s.close()运行结果:
HTTP/1.1 200 OK Server: nginx Date: Mon, 30 Jul 2018 15:27:31 GMT Content-Type: text/html Content-Length: 569784 Connection: close Last-Modified: Mon, 30 Jul 2018 15:24:01 GMT Vary: Accept-Encoding X-Powered-By: shci_v1.03 Expires: Mon, 30 Jul 2018 15:28:06 GMT Cache-Control: max-age=60 Age: 14 Via: http/1.1 gwbn.guangzhou.ha2ts4.26 (ApacheTrafficServer/6.2.1 [cHs f ]), http/1.1 gwbn.shanghai.ha2ts4.19 (ApacheTrafficServer/6.2.1 [cHs f ]) X-Via-Edge: 1532964451960c86fc48b09010e7c77e64765 X-Cache: HIT.19 X-Via-CDN: f=edge,s=gwbn.shanghai.ha2ts4.18.nb.sinaedge.com,c=139.196.111.200;f=Edge,s=gwbn.shanghai.ha2ts4.19,c=124.14.1.18 : :
在python3中运行出错:
运行结果:
Traceback (most recent call last): File "/usercode/file.py", line 16, ins.send('GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n') TypeError: 'str' does not support the buffer interface
这是因为python3对字符串做了更改,使得默认字符串编码与python2.7的不同。
所以,使用client_socket.send(data)时,将其替换为client_socket.send(data.encode())。
当使用data = client_socket.recv(512)获取数据时,请将其替换为data = client_socket.recv(512).decode()
更改后的程序为:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 导入socket库:
import socket
# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('www.sina.com.cn', 80))
s.send(('GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n').encode()) ####添加.encode
# 接收数据:
buffer = []
while True:
# 每次最多接收1k字节:
d = s.recv(1024).decode("utf8","ignore") #######添加.decode("utf8","ignore")
if d:
buffer.append(d)
else:
break
data = ''.join(buffer)
print (data)
# 关闭连接:
s.close()运行结果:
HTTP/1.1 200 OK Server: nginx Date: Mon, 30 Jul 2018 16:00:02 GMT Content-Type: text/html Content-Length: 569807 Connection: close Last-Modified: Mon, 30 Jul 2018 15:57:02 GMT Vary: Accept-Encoding X-Powered-By: shci_v1.03 Expires: Mon, 30 Jul 2018 16:00:35 GMT Cache-Control: max-age=60 Age: 31 Via: http/1.1 gwbn.guangzhou.ha2ts4.26 (ApacheTrafficServer/6.2.1 [cHs f ]), http/1.1 gwbn.shanghai.ha2ts4.19 (ApacheTrafficServer/6.2.1 [cHs f ]) X-Via-Edge: 1532966402856de110e6a09010e7c4a141492 X-Cache: HIT.19 X-Via-CDN: f=edge,s=gwbn.shanghai.ha2ts4.19.nb.sinaedge.com,c=106.14.17.222;f=Edge,s=gwbn.shanghai.ha2ts4.19,c=124.14.1.19 : :
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。