问题描述
import socket
backlog = 1 #Number of queues
sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local = {"port":1433}
internet = {"port":9999}
sk_1.bind (('', internet["port"]))
sk_1.listen(backlog)
sk_2.bind (('', local["port"]))
sk_2.listen(backlog)
基本上,我有这段代码.我试图在两个端口上监听:1433和9999.但是,这似乎不起作用.
Basically, I have this code. I am trying to listen on two ports: 1433 and 9999. But, this doesn't seems to work.
我如何在同一个python脚本中的两个端口上侦听?
How can I listen on two ports, within the same python script??
推荐答案
如果要使用Python std-lib,这样做的花哨方法是将SocketServer与ThreadingMixin一起使用-尽管选择"建议可能更有效.
The fancy-pants way to do this if you want to use Python std-lib would be to use SocketServer with the ThreadingMixin -- although the 'select' suggestion is probably the more efficient.
即使我们只定义了一个ThreadedTCPRequestHandler,您也可以轻松地重新使用它,以便每个侦听器都有自己的唯一处理程序,并且如果您喜欢这种方法,则将服务器/线程创建包装到单个方法中应该是很简单的.
Even though we only define one ThreadedTCPRequestHandler you can easily repurpose it such that each listener has it's own unique handler and it should be fairly trivial to wrap the server/thread creation into a single method if thats the kind of thing you like.
#!/usr/bin/python
import threading
import time
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print "%s wrote: " % self.client_address[0]
print self.data
self.request.send(self.data.upper())
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
HOST = ''
PORT_A = 9999
PORT_B = 9876
server_A = ThreadedTCPServer((HOST, PORT_A), ThreadedTCPRequestHandler)
server_B = ThreadedTCPServer((HOST, PORT_B), ThreadedTCPRequestHandler)
server_A_thread = threading.Thread(target=server_A.serve_forever)
server_B_thread = threading.Thread(target=server_B.serve_forever)
server_A_thread.setDaemon(True)
server_B_thread.setDaemon(True)
server_A_thread.start()
server_B_thread.start()
while 1:
time.sleep(1)
这篇关于Python:在两个端口上监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!