我试图用python的SocketServer模块绑定多个服务器:
import SocketServer
from SocketServer import BaseRequestHandler
class HTTPSERVER(BaseRequestHandler):
def handle(self):
rec = self.request.recv(1024)
if rec:
self.request.send('Got something!')
launchme = SocketServer.TCPServer(('', 82),HTTPSERVER)
launchme2 = SocketServer.TCPServer(('', 81),HTTPSERVER)
launchme3 = SocketServer.TCPServer(('', 80),HTTPSERVER)
launchme.serve_forever()
print 'reached first server'
launchme2.serve_forever()
print 'reached second server'
launchme3.serve_forever()
print 'reached third server'
当启动此脚本时,没有任何内容被打印,但所有3个端口实际上都是打开的:
root@user:/# netstat -pna|more
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 2751/python
tcp 0 0 0.0.0.0:81 0.0.0.0:* LISTEN 2751/python
tcp 0 0 0.0.0.0:82 0.0.0.0:* LISTEN 2751/python
但是这个剧本只服务于某事!'当请求在端口82上进行时(第一次绑定)。使用SocketServer模块使所有端口正常工作的正确方法是什么?
答案 0 :(得分:2)
server_forever
处理请求,直到明确的shutdown()请求。
调用launchme.serve_forever()
后,将不会调用下一个。{1}}。您需要在线程或分离的进程中调用它们。
import SocketServer
from SocketServer import BaseRequestHandler
import threading
class HTTPSERVER(BaseRequestHandler):
def handle(self):
rec = self.request.recv(1024)
if rec:
self.request.send('Got something!')
launchme = SocketServer.TCPServer(('', 82),HTTPSERVER)
launchme2 = SocketServer.TCPServer(('', 81),HTTPSERVER)
launchme3 = SocketServer.TCPServer(('', 80),HTTPSERVER)
t1 = threading.Thread(target=launchme.serve_forever)
t2 = threading.Thread(target=launchme2.serve_forever)
t3 = threading.Thread(target=launchme3.serve_forever)
for t in t1, t2, t3: t.start()
for t in t1, t2, t3: t.join()
答案 1 :(得分:0)