1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| # -*- coding: UTF-8 -*-
import json import struct import socket import time
def loop(s, handlers): while True: conn, addr = s.accept() handle_conn(conn, addr, handlers) # 处理连接
def handle_conn(conn, addr, handlers): print(addr, "comes") while True: # 循环读写 length_prefix = conn.recv(4) # 请求长度前缀 if not length_prefix: # 连接关闭了 print addr, "bye" conn.close() break # 退出循环,处理下一个连接 length, = struct.unpack("I", length_prefix) body = conn.recv(length).decode() # 请求消息体 request = json.loads(body) in_ = request['in'] params = request['params'] print( in_, params) handler = handlers[in_] # 查找请求处理器 handler(conn, params) # 处理请求...
def send_result(conn, out, result): response = json.dumps({"out": out, "result": result}) # 响应消息体 length_prefix = struct.pack("I", len(response)) # 响应长度前缀 conn.sendall(length_prefix) conn.sendall(response.encode())
def ping(conn, params): send_result(conn, "pong", params)
if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 打开 reuse addr 选项 s.bind(("localhost", 8080)) s.listen(1) handlers = { "ping": ping } loop(s, handlers)
|