Web應用通信通常都喜歡用HTTP接口,但不排除直接socket通信的情況。
socket除了server端構建麻煩些(需要考慮很多實際情況),對於調用者來說構建個client端其實不比http麻煩多少。
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- # Auther: linvo
-
- import socket
-
-
- class 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 socket
- sock = 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()