以下範例整理自《Foundations of Python Network Programming》,執行環境為 Python 2.7。這是最直觀的客戶端/伺服器結構:伺服器一次只服務一位客戶,處理完才接受下一個連線。
# !/usr/bin/env python
import socket, sys
PORT = 1060
qa = (('What is your name?', 'My name is Sir Lanucelot of Camelot.'),
('what is your request?', 'To seek the Holy Grail.'),
('what is your favourite color?', 'Bule.'))
qadict = dict(qa)
def recv_until(sock, suffix):
message = ''
# 以特定符號斷句;此處為阻塞行為,直到 suffix 出現才返回
while not message.endswith(suffix):
data = sock.recv(4096) # 單次接收的最大位元組數
if not data:
raise EOFError('socket closed before we saw %r' % suffix)
message += data
return message
def setup():
interface = 'localhost'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, PORT))
sock.listen(128) # 佇列上限
print 'Ready and listening at %r port %d' % (interface, PORT)
return sock
recv_until 是這個範例的核心:TCP 是串流,沒有訊息邊界,因此靠自訂的結束符號(問號與句點)來切分訊息。SO_REUSEADDR 則讓重啟伺服器時不會卡在 address already in use。
# !/usr/bin/env python
import launcelot
def handle_client(client_sock):
try:
while True:
question = launcelot.recv_until(client_sock, '?')
answer = launcelot.qadict[question]
client_sock.sendall(answer)
except EOFError:
client_sock.close()
def server_loop(listen_sock):
while True:
client_sock, sockname = listen_sock.accept()
handle_client(client_sock)
if __name__ == '__main__':
listen_sock = launcelot.setup()
server_loop(listen_sock)
# !/usr/bin/env python
import sys, socket, launcelot, os
def client(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(launcelot.qa[0][0])
answer1 = launcelot.recv_until(s, '.')
s.sendall(launcelot.qa[1][0])
answer2 = launcelot.recv_until(s, '.')
s.sendall(launcelot.qa[2][0])
answer3 = launcelot.recv_until(s, '.')
s.close()
print answer1
print answer2
print answer3
if __name__ == '__main__':
client('localhost', 1060)
單執行緒的結構在 handle_client 結束前無法接受新連線,因此只要有一位客戶慢慢不講話,其他人就被鎖在門外。實務上的演進路徑很明確:先 fork 或 thread 讓每個連線獨立,再往 select/poll 的事件迴圈,最後是 asyncio 這類非同步 I/O。理解這個雛形,後面的模型才會來得有依據。