標籤:bin data code ret pen last 100% else ping
在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: breakdata = ''.join(buffer)print (data)# 關閉串連:s.close()
運行結果:
HTTP/1.1 200 OKServer: nginxDate: Mon, 30 Jul 2018 15:27:31 GMTContent-Type: text/htmlContent-Length: 569784Connection: closeLast-Modified: Mon, 30 Jul 2018 15:24:01 GMTVary: Accept-EncodingX-Powered-By: shci_v1.03Expires: Mon, 30 Jul 2018 15:28:06 GMTCache-Control: max-age=60Age: 14Via: 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: 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<!DOCTYPE html><!-- [ published at 2018-07-30 23:24:00 ] --><html><head>::
在python3中運行出錯:
運行結果:
Traceback (most recent call last): File "/usercode/file.py", line 16, in <module> s.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: breakdata = ''.join(buffer)print (data)# 關閉串連:s.close()
運行結果:
HTTP/1.1 200 OKServer: nginxDate: Mon, 30 Jul 2018 16:00:02 GMTContent-Type: text/htmlContent-Length: 569807Connection: closeLast-Modified: Mon, 30 Jul 2018 15:57:02 GMTVary: Accept-EncodingX-Powered-By: shci_v1.03Expires: Mon, 30 Jul 2018 16:00:35 GMTCache-Control: max-age=60Age: 31Via: 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: 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<!DOCTYPE html><!-- [ published at 2018-07-30 23:57:00 ] --><html>::
python 網路編程:TCP