00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 import socket
00029 import cPickle
00030 import sys
00031
00032 DNS_CACHE = {}
00033
00034 class Myexception(Exception):
00035 def __init__(self, faultCode, faultString):
00036 self.faultCode = faultCode
00037 self.faultString = faultString
00038 self.args = (faultCode, faultString)
00039
00040 class mysocket:
00041 def __init__(self, sock=None):
00042 if sock is None:
00043 self.sock = socket.socket(
00044 socket.AF_INET, socket.SOCK_STREAM)
00045 else:
00046 self.sock = sock
00047 self.sock.settimeout(120)
00048 def connect(self, host, port=False):
00049 if not port:
00050 protocol, buf = host.split('//')
00051 host, port = buf.split(':')
00052 if host in DNS_CACHE:
00053 host = DNS_CACHE[host]
00054 self.sock.connect((host, int(port)))
00055 DNS_CACHE[host], port = self.sock.getpeername()
00056 def disconnect(self):
00057
00058
00059 if sys.platform != 'darwin':
00060 self.sock.shutdown(socket.SHUT_RDWR)
00061 self.sock.close()
00062 def mysend(self, msg, exception=False, traceback=None):
00063 msg = cPickle.dumps([msg,traceback])
00064 size = len(msg)
00065 self.sock.send('%8d' % size)
00066 self.sock.send(exception and "1" or "0")
00067 totalsent = 0
00068 while totalsent < size:
00069 sent = self.sock.send(msg[totalsent:])
00070 if sent == 0:
00071 raise RuntimeError, "socket connection broken"
00072 totalsent = totalsent + sent
00073 def myreceive(self):
00074 buf=''
00075 while len(buf) < 8:
00076 chunk = self.sock.recv(8 - len(buf))
00077 if chunk == '':
00078 raise RuntimeError, "socket connection broken"
00079 buf += chunk
00080 size = int(buf)
00081 buf = self.sock.recv(1)
00082 if buf != "0":
00083 exception = buf
00084 else:
00085 exception = False
00086 msg = ''
00087 while len(msg) < size:
00088 chunk = self.sock.recv(size-len(msg))
00089 if chunk == '':
00090 raise RuntimeError, "socket connection broken"
00091 msg = msg + chunk
00092 res = cPickle.loads(msg)
00093 if isinstance(res[0],Exception):
00094 if exception:
00095 raise Myexception(str(res[0]), str(res[1]))
00096 raise res[0]
00097 else:
00098 return res[0]