2010-03-22 79 views
0

親愛的所有人,我需要在Python中實現一個TCP服務器,它從客戶端接收一些數據,然後將這些數據發送到另一個客戶端。我嘗試了許多不同的實現,但沒有辦法讓它運行。任何幫助將非常感激。
下面是我的代碼:如何在Python中實現集線器

import SocketServer 
import sys 
import threading 

buffer_size = 8182 
ports = {'toserver': int(sys.argv[1]), 'fromserver': int(sys.argv[2])} 

class ConnectionHandler(SocketServer.BaseRequestHandler): 

    def handle(self): 
     # I need to send the data received from the client connected to port 'toserver' 
     # to the client connected to port 'fromserver' - see variable 'ports' above 

class TwoWayConnectionServer(threading.Thread): 

    def __init__(self): 
     self.to_server = SocketServer.ThreadingTCPServer(("", ports['toserver']), ConnectionHandler) 
     self.from_server = SocketServer.ThreadingTCPServer(("", ports['fromserver']), ConnectionHandler) 
     threading.Thread.__init__(self) 

    def run(self): 
     while (1): 
      self.to_server.handle_request() 
      self.from_server.handle_request() 

def serve_non_blocking(): 

    server = TwoWayConnectionServer() 
    server.run() 

if __name__ == '__main__': 

    serve_non_blocking() 
+1

你需要更具體。你是什​​麼意思「讓它運行」?你不能啓動程序嗎? – unwind 2010-03-22 16:24:44

回答

0

你能具體談談你嘗試過什麼,什麼沒有奏效?有很多方法可以做到這一點。也許最簡單的辦法是使用套接字庫 - 也許在看一些例子可以幫助:

http://docs.python.org/library/socket.html#example

+0

看到我添加到我的問題的代碼... – j3d 2010-03-24 11:46:20

1

Twisted tutorial,也twisted.protocols.portforward。我認爲portforward模塊與你想要的有些不同,它會打開到目的端口的傳出連接,而不是等待第二個客戶端連接,但你應該可以從那裏工作。

+0

我已經添加了一些代碼給我的問題(見上文)。例如,是否可以從一個客戶端(端口'toserver')接收數據並直接將其轉發給另一個客戶端(端口'fromserfver')?還是有必要緩存傳入的數據,並在目標客戶端發送一條請求獲取此數據的消息後立即將其發送到目標客戶端?謝謝,傑夫 – j3d 2010-03-24 10:47:31

+0

我想你可能想緩衝,如果沒有什麼東西連接到'from_server',但否則''to_server'上的處理程序可能看起來像'def dataReceived(self,data):from_server.write(data)' 。 – keturn 2010-03-24 20:17:57