# 導入socket庫:
import socket
# 建立一個socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 創建鏈接:
s.connect(('www.sina.com.cn', 80))
建立socket時, socket.AF_INET
表明使用用IPv4協議, 若是要使用IPv6協議, 則指定sockt.AF_INET6
, SOCK_STREAM
指定使用面向流的TCP協議.html
s.send(b'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 = b''.join(buffer)
# 關閉鏈接:
s.close()
# 處理數據
header, html = response.split(b'\r\n\r\n', 1)
print(header.decode("utf-8"))
print(html.decode('utf-8'))
socket默認是堵塞的, 當socket運行connect()
,recv()
方法時, 會堵塞直到運行完成.python
sock = socket.socket()
#將socket設爲非堵塞的self.
sock.setblocking(False)
這樣作會直接拋出一個BlockingIOError
的異常, 詳細內容A non-blocking socket operation could not be completed immediately
,編程
解決方法:服務器
try:
sock.connect(('xkcd.com', 80))
except BlockingIOError:
pass
request = 'GET {} HTTP/1.0\r\nHost: xkcd.com\r\n\r\n'.format(url)
encoded=request.encode('ascii')
sock.send(encoded)
也會拋出異常OSError: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
markdown
解決方法:併發
while True:
try:
sock.send(encoded)
break # Done.
except OSError as e:
pass