使用python socketserver连接到多个端口

时间:2016-02-08 21:27:06

标签: python sockets python-multithreading tcp-ip socketserver

好的,尝试将一些C ++代码移植到python。对于这种特定情况,我需要设置TCP / IP服务器以接受多个端口上的通信。在旧的C ++代码中,对应于每个端口创建了多个casyncsocket实例。

我想使用python 3做同样的事情。通过其他示例,我试图修改一个工作。下面我添加了一些额外的行来尝试连接到1520和1525端口。

#!/usr/bin/env python


import socketserver
from threading import Thread

class service(socketserver.BaseRequestHandler):
    def handle(self):
        data = 'dummy'
        print ("Client connected with ", self.client_address)
        while len(data):
            data = self.request.recv(1024)
            self.request.send(data)

        print ("Client exited")
        self.request.close()


class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

t = ThreadedTCPServer(('',1520), service)


m = ThreadedTCPServer(('',1525), service)

t.serve_forever()
m.serve_forever()

每次运行上面的命令都会出错。如果我拿出

m = ThreadedTCPServer(('',1525), service)
m.serve_forever()

然后它工作正常。 我是初学者,如果socket编程和python,并没有太多的运气找到例子。任何帮助表示赞赏。

更新

好吧,看来我找到了一个有效的解决方案。

import threading
import socketserver


class Datahandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(2048)

        if self.data:
            self.request.sendall(self.data)


class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


def main():
    global TDC_servers
    global TDC_server_threads

    TDC_servers = []
    TDC_server_threads =[]

    TDC_servers.append(ThreadedTCPServer(('', 1520), Datahandler))
    TDC_servers.append(ThreadedTCPServer(('', 1525), Datahandler))

    for TDC_server in TDC_servers:
        TDC_server_threads.append(threading.Thread(target=TDC_server.serve_forever))

    for TDC_server_thread in TDC_server_threads:
        TDC_server_thread.setDaemon(True)
        TDC_server_thread.start()

    while True:
        continue


if __name__ == '__main__':
    try:
        main()


    finally:
        print('quitting servers')

        for TDC_server in TDC_servers:
            TDC_server.server_close()

0 个答案:

没有答案