1
我試圖在Python中編寫客戶端服務器應用程序,但我遇到了一個問題,在客戶端,我沒有得到所有發送的數據。首先我試着發送1到10的數字,我收到1,2,5,6,10,所以缺少很多數字。Python丟失包
服務器端:
def __init__(self):
super(MCCommunication, self).__init__()
HOST, PORT = socket.gethostbyname(socket.gethostname()), 31000
self.server = SocketServer.ThreadingTCPServer((HOST, PORT), MCRequestHandler)
ip, port = self.server.server_address
# Start a thread with the server
# Future task: Make the server a QT-Thread...
self.server_thread = threading.Thread(target = self.server.serve_forever)
# Exit the server thread when the main thread terminates
self.server_thread.setDaemon(True)
self.textUpdated.emit('Server Started!')
print('Server Started!')
self.server_thread.start()
def handle(self):
#self.request.setblocking(0)
i = 10;
while True:
if(self.clientname == 'MasterClient'):
try:
#ans = self.request.recv(4096)
#print('after recv')
""" Sendign data, testing purpose """
while i:
mess = str(i);
postbox['MasterClient'].put(self.creatMessage(0, 0 , mess))
i = i - 1
while(postbox['MasterClient'].empty() != True):
sendData = postbox['MasterClient'].get_nowait()
a = self.request.send(sendData)
print(a);
#dic = self.getMessage(sendData)
#print 'Sent:%s\n' % str(dic)
except:
mess = str(sys.exc_info()[0])
postbox['MasterClient'].put(self.creatMessage(1, 0 , mess))
pass
def creatMessage(self, type1 = 0, type2 = 0, message = ' ', extra = 0):
return pickle.dumps({"type1":type1, "type2":type2, "message":message, "extra":extra});
凡postbox['MasterClient']
是與序列化消息的隊列。
這是客戶端:
def run(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = (self.ip, self.port)
#print addr
sock.connect(addr)
#sock.setblocking(0)
while True:
try:
ans = sock.recv(4096)
dic = self.getMessage(ans)
self.recvMessageHandler(dic)
print 'Received:%s\n' % str(dic)
except:
pass