Python socket 模組提供 BSD 風格網路 API。本文涵蓋 TCP Socket 建立、連線、發送/接收資料、伺服端監聽迴圈、Python 2/3 字串/位元組差異與錯誤處理。
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 預設值,可省略
s.connect(('www.example.com', 80)) # 或 ('127.0.0.1', 8000)
# 發送:sendall 保證全送出
s.sendall(b'GET / HTTP/1.0\r\n\r\n') # Python 3 需 bytes
# 接收:迴圈讀取直到指定長度或連線關閉
def recv_all(sock, length):
data = b''
while len(data) < length:
chunk = sock.recv(min(length - len(data), 2048))
if not chunk:
raise RuntimeError("socket connection broken")
data += chunk
return data
| 操作 | Python 2 | Python 3 |
|---|---|---|
| sendall 參數 | str | bytes |
| recv 回傳 | str | bytes |
| 字串字面值 | 'abc' | b'abc' 或 encode() |
建議:統一使用 bytes 處理網路資料,應用層自行編解碼。
import socket
HOST, PORT = '', 10022
s = socket.socket()
s.bind((HOST, PORT))
s.listen(10)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
import socket
s = socket.socket()
s.connect(('localhost', 10022))
s.sendall(b'hello socket')
print('Received', repr(s.recv(1024)))
s.close()
try:
s = socket.socket()
s.bind((HOST, PORT))
s.listen(10)
except socket.error as e:
print("Socket error:", e)
常見例外:socket.error、socket.gaierror (解析失敗)、socket.timeout、socket.herror。
不再使用時呼叫 s.close() 釋放檔案描述符。with 陳述式不直接支援 socket,需自行實作 context manager 或使用 contextlib.closing。