2013-11-15 53 views
1

我想實現一個簡單的線程SocketServer(使用SocketServer.ThreadedMixIn)。但是,我的服務器停止接收更多消息。下面是代碼:螺紋SocketServer沒有收到第二條消息

#!/usr/bin/python -u 
import SocketServer 
import sys 

class MYAgentHandler(SocketServer.BaseRequestHandler): 
    def handle(self): 
     try: 
      data = self.request.recv(1024) 
      print "Received request " + str(data) + "\n" 
      reply = str(agent.processAgentMessage(data)) 
      self.request.send(reply) 
      self.request.close() 
     except Exception, instr: 
      print "While processing data " + data + " error encountered " + str(instr) + "\n" 

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): 
    daemon_threads = True 
    allow_reuse_address = True 
    def __init__(self, server_address, RequestHandlerClass): 
     SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) 

class MYAgent: 
    def processAgentMessage(self, msg): 
     try: 
      tokens = msg.split('^') 
      if tokens[0] == "CreateSession": 
       return("New session") 
      elif tokens[0] == "GetStatus": 
       return("Init") 
     except Exception, instr: 
      print "Error while processing message " + str(instr) + "\n" 

agent = MYAgent() 

def main(): 
    MYServer = sys.argv[1] 
    MYAgentPort = sys.argv[2] 
    agent.listener = ThreadedTCPServer((MYServer, int(MYAgentPort)), MYAgentHandler) 
    agent.listener.serve_forever() 

if __name__ == '__main__': 
    main() 

這裏是我的客戶:

#!/usr/bin/python -u 
import socket 
import time 
if __name__ == "__main__": 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    sock.connect(('localhost', 15222)) 
    try: 
     sock.send("CreateSession") 
     sessionID = str(sock.recv(1024)) 
     print "Received: " + sessionID 
     sock.send("GetStatus^"+sessionID) 
     print "Sent Getstatus\n" 
     time.sleep(1) 
     response = str(sock.recv(1024)) 
     print "status of " + str(sessionID) + " is " + str(response) + "\n" 
     sock.close() 
    except Exception, instr: 
     print "Error occurred " + str(instr) + "\n" 

這是一個會話。服務器輸出:

$ ./t.py localhost 15222 
Received request CreateSession 

客戶端輸出:

$ ./client.py 
Received: New session 
Sent Getstatus 

status of New session is 

$ 

任何想法,爲什麼發生這種情況?

+0

'self.request.close()'您在收到第一條消息後明確關閉連接。 – freakish

+0

我從示例中解除了代碼。我嘗試了沒有關閉,也沒有工作。 – PythonNerd

+0

是的,因爲你只讀過一次。刪除'self.request.close()'並用'while True:'循環包裝整個方法。 – freakish

回答

0

你必須刪除self.request.close()(它關閉連接)並用while True:(所以它會繼續從同一個套接字讀取)將所有東西都包裹起來。