Python调用远程Socket接口


Web应用通信通常都喜欢用HTTP接口,但不排除直接socket通信的情况。

socket除了server端构建麻烦些(需要考虑很多实际情况),对于调用者来说构建个client端其实不比http麻烦多少。

 
  1. #!/usr/bin/env python   
  2. # -*- coding:utf-8 -*-   
  3. # Auther: linvo   
  4.   
  5. import socket  
  6.   
  7.   
  8. class Client(object):  
  9.     """ 
  10.     调用远程Socket接口 
  11.     <code> 
  12.     try: 
  13.         obj = Client(host, port) 
  14.         ret = obj.send(data) 
  15.     except Exception, e: 
  16.         ret = e 
  17.     </code> 
  18.     """  
  19.     def __init__(self, host, port, timeout = 5):  
  20.         """ 
  21.         链接远程接口服务 
  22.         """  
  23.         self.sock = None  
  24.         try:  
  25.             socket.setdefaulttimeout(timeout)   
  26.             self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   
  27.             self.sock.connect((host, port))  
  28.         except socket.error, e:  
  29.             raise Exception('SOCKET ERROR:' + str(e))  
  30.         except Exception, e:  
  31.             raise Exception('CONNECT ERROR:' + str(e))  
  32.   
  33.   
  34.   
  35.     def send(self, data):  
  36.         """ 
  37.         socket通信 
  38.         发送和接收 
  39.         data: 发送的数据 
  40.         ret: 接收的数据 
  41.         """  
  42.         ret = None  
  43.         # 链接成功,开始传输   
  44.         if self.sock:  
  45.             data = str(data)  
  46.             try:  
  47.                 result = self.sock.sendall(data)  
  48.             except Exception, e:  
  49.                 result = str(e)  
  50.   
  51.             if result is not None:  
  52.                 raise Exception('SEND ERROR:' + str(result))  
  53.             else:  
  54.                 # 接收    
  55.                 ret = ''  
  56.                 try:  
  57.                     while True:  
  58.                         buffer = self.sock.recv(2048)  
  59.                         if buffer:   
  60.                             ret += buffer  
  61.                         else:  
  62.                             break  
  63.                 except Exception, e:  
  64.                     raise Exception('RECV ERROR:' + str(e))  
  65.         return ret  

顺便给个简易的server端,以便测试: 

 
  1. import socket  
  2. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  3. sock.bind(('localhost'9801))  
  4. sock.listen(5)  
  5. while True:  
  6.     connection, address = sock.accept()  
  7.     try:  
  8.         connection.settimeout(5)  
  9.         buf = connection.recv(2048)  
  10.         connection.send(buf)  
  11.     except socket.timeout:  
  12.         print 'time out'  
  13.     connection.close()  

相关内容