Web應用通訊通常都喜歡用HTTP介面,但不排除直接socket通訊的情況。
socket除了server端構建麻煩些(需要考慮很多實際情況),對於調用者來說構建個client端其實不比http麻煩多少。
#!/usr/bin/env python# -*- coding:utf-8 -*-# Auther: linvoimport socketclass Client(object): """ 調用遠程Socket介面 <code> try: obj = Client(host, port) ret = obj.send(data) except Exception, e: ret = e </code> """ def __init__(self, host, port, timeout = 5): """ 連結遠程介面服務 """ self.sock = None try: socket.setdefaulttimeout(timeout) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) except socket.error, e: raise Exception('SOCKET ERROR:' + str(e)) except Exception, e: raise Exception('CONNECT ERROR:' + str(e)) def send(self, data): """ socket通訊 發送和接收 data: 發送的資料 ret: 接收的資料 """ ret = None # 連結成功,開始傳輸 if self.sock: data = str(data) try: result = self.sock.sendall(data) except Exception, e: result = str(e) if result is not None: raise Exception('SEND ERROR:' + str(result)) else: # 接收 ret = '' try: while True: buffer = self.sock.recv(2048) if buffer: ret += buffer else: break except Exception, e: raise Exception('RECV ERROR:' + str(e)) return ret
順便給個簡易的server端,以便測試:
import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.bind(('localhost', 9801))sock.listen(5)while True: connection, address = sock.accept() try: connection.settimeout(5) buf = connection.recv(2048) connection.send(buf) except socket.timeout: print 'time out' connection.close()