python 网络编程:TCP
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 网络编程:TCP相关的知识,希望对你有一定的参考价值。
在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 Host: www.sina.com.cn Connection: close ') # 接收数据: 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 <!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 Host: www.sina.com.cn Connection: close ') 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 Host: www.sina.com.cn Connection: close ').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 <!DOCTYPE html> <!-- [ published at 2018-07-30 23:57:00 ] --> <html> : :
以上是关于python 网络编程:TCP的主要内容,如果未能解决你的问题,请参考以下文章