在python2.7中完好运行:

#!/usr/bin/python#-*-coding:utf-8-*-#导入socket库:importsocket#创建一个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=[]whileTrue:#每次最多接收1k字节:d=s.recv(1024)ifd:buffer.append(d)else:breakdata=''.join(buffer)print(data)#关闭连接:s.close()

运行结果:

HTTP/1.1200OKServer:nginxDate:Mon,30Jul201815:27:31GMTContent-Type:text/htmlContent-Length:569784Connection:closeLast-Modified:Mon,30Jul201815:24:01GMTVary:Accept-EncodingX-Powered-By:shci_v1.03Expires:Mon,30Jul201815:28:06GMTCache-Control:max-age=60Age:14Via:http/1.1gwbn.guangzhou.ha2ts4.26(ApacheTrafficServer/6.2.1[cHsf]),http/1.1gwbn.shanghai.ha2ts4.19(ApacheTrafficServer/6.2.1[cHsf])X-Via-Edge:1532964451960c86fc48b09010e7c77e64765X-Cache:HIT.19X-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<!DOCTYPEhtml><!--[publishedat2018-07-3023:24:00]--><html><head>::


在python3中运行出错:

运行结果:

Traceback(mostrecentcalllast):File"/usercode/file.py",line16,in<module>s.send('GET/HTTP/1.1\r\nHost:www.sina.com.cn\r\nConnection:close\r\n\r\n')TypeError:'str'doesnotsupportthebufferinterface


这是因为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库:importsocket#创建一个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=[]whileTrue:#每次最多接收1k字节:d=s.recv(1024).decode("utf8","ignore")#######添加.decode("utf8","ignore")ifd:buffer.append(d)else:breakdata=''.join(buffer)print(data)#关闭连接:s.close()

运行结果:

HTTP/1.1200OKServer:nginxDate:Mon,30Jul201816:00:02GMTContent-Type:text/htmlContent-Length:569807Connection:closeLast-Modified:Mon,30Jul201815:57:02GMTVary:Accept-EncodingX-Powered-By:shci_v1.03Expires:Mon,30Jul201816:00:35GMTCache-Control:max-age=60Age:31Via:http/1.1gwbn.guangzhou.ha2ts4.26(ApacheTrafficServer/6.2.1[cHsf]),http/1.1gwbn.shanghai.ha2ts4.19(ApacheTrafficServer/6.2.1[cHsf])X-Via-Edge:1532966402856de110e6a09010e7c4a141492X-Cache:HIT.19X-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<!DOCTYPEhtml><!--[publishedat2018-07-3023:57:00]--><html>::