Python调用远程Socket接口
Web应用通信通常都喜欢用HTTP接口,但不排除直接socket通信的情况。
socket除了server端构建麻烦些(需要考虑很多实际情况),对于调用者来说构建个client端其实不比http麻烦多少。
-
-
-
-
- import socket
-
-
- class Client(object):
-
-
-
-
-
-
-
-
-
-
- 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):
-
-
-
-
-
-
- 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()
|
评论暂时关闭