2013-06-30 28 views
1

幫助建立python分叉TCPServer。當客戶端連接到服務器時,此服務器返回錯誤。當我使用ThreadingTCPServer而不是ForkingTCPServer時,它工作正常。 socketFileIO模塊包含鹹菜功能/從插座: http://code.activestate.com/recipes/577667-pickle-tofrom-socket/Python分叉TCPServer錯誤

server.py:

import SocketServer, time 
from socketFileIO import write, read 

class MyClientHandler(SocketServer.BaseRequestHandler): 
    def handle(self): 
     print self.client_address 
     data=read(self.request) 
     print 'Client:', data 
     time.sleep(10) # for testing 
     write(self.request,data) 
     self.request.close() 

HOST, PORT = '', 50007 
server = SocketServer.ForkingTCPServer((HOST, PORT), MyClientHandler) 
server.serve_forever() 

client.py:

import socket 
from socketFileIO import write, read 
HOST = '127.0.0.1' 
PORT = 50007 
data=["A","B","C","End"] 
for x in data: 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((HOST, PORT)) 
    write(s,x) 
    y=read(s) 
    print 'Server:', y 
    s.close() 

錯誤:

---------------------------------------- 
Exception happened during processing of request from ('127.0.0.1', 1469) 
Traceback (most recent call last): 
    File "c:\Python26\lib\SocketServer.py", line 283, in _handle_request_noblock 
    self.process_request(request, client_address) 
    File "c:\Python26\lib\SocketServer.py", line 525, in process_request 
    pid = os.fork() 
AttributeError: 'module' object has no attribute 'fork' 
---------------------------------------- 

我有其他幾個問題:

  1. 如何通過從客戶端發送數據「End」關閉服務器?
  2. 如何限制連接數量(例如不超過5)?
+2

'os.fork'在Windows上不可用。 – Blender

+0

謝謝!換句話說SocketServer.ForkingTCPServer無法在Windows上工作? –

+1

沒有。你或許可以用Twisted或'multithreading'寫一些類似的東西。 – Blender

回答

1

您的分叉問題已在評論中回答。對於「如何關閉服務器」:在一個類似的應用程序中(但是Python版本比較老,使用xmlrpc),我一次使用一個循環調用一個請求,直到設置了一個「停止」變量。這似乎現在在Python 2.7中直接支持:在線程服務器中,從請求處理程序線程之一調用服務器實例上的shutdown()。 (不知道這是可以在2.6,我去裝我的老版本2.6幾個月前。),即:

class MyClientHandler(SocketServer.BaseRequestHandler): 
    def handle(self): 
     ... 
     # if we're supposed to shut down the server, do that 
     if somecond: 
      self.server.shutdown() 

爲了限制連接數:沒有什麼內置的,我可以看到,但是如果你重新定義了process_request處理程序,你可以計算活動線程的數量,並等待一個完成,如果有「太多」未完成的(或者工作但不管你喜歡)。請參閱SocketServer.py中的ThreadingMixIn類,並將其與ForkingMixIn中的max_children代碼進行比較。