鍍金池/ 問答/Java  Python  網(wǎng)絡安全/ socket 接受數(shù)據(jù)會停頓

socket 接受數(shù)據(jù)會停頓

開始學習socket(python)中遇到問題,
廖雪峰的socket學習網(wǎng)站:
https://www.liaoxuefeng.com/w...
問題:在while循環(huán)接受百度的返回內容的時候,最后一次接受會停留很長時間,正常的訪問請求肯定沒有那么慢,不知道什么問題。
附上自己的代碼:

# 導入socket庫:
import socket

# 創(chuàng)建一個socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立連接:
s.connect(('www.baidu.com', 80))
# 發(fā)送數(shù)據(jù):
s.send(b'GET / HTTP/1.1\r\nHost:www.baidu.com\r\n\r\n')

# 接收數(shù)據(jù):
buffer = []
while True:
    # 每次最多接收1k字節(jié):
    d = s.recv(1024)
    #每次接受1024字節(jié),但是當d==""的接受會停留很長時間
    print(d)
    if d:
        buffer.append(d)
    else:
        break
data = b''.join(buffer)
s.close()
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
# 把接收的數(shù)據(jù)寫入文件:
with open('sina.html', 'wb') as f:
    f.write(html)

停好幾秒(紅框)

clipboard.png

回答
編輯回答
來守候
s.send(b'GET / HTTP/1.1\r\nHost:www.baidu.com\r\nConnection: close\r\n\r\n')

請求完主動關閉

2017年5月2日 06:04