[英]python listen 2 port same file
I would like to listen on 2 different UDP port with the same server. 我想用同一台服务器监听2个不同的UDP端口。 I use SocketServer lib for my server, and basicly it looks like that;
我为我的服务器使用SocketServer lib,基本上它看起来像那样;
SocketServer.UDPServer(('', 7878),CLASSNAME) SocketServer.UDPServer(('',7878),CLASSNAME)
I would like to listen on 7878 and 7879 with the same server and same file. 我想听7878和7879使用相同的服务器和相同的文件。 Is that possible?
那可能吗? If yes how?
如果有,怎么样?
Sure you can, using threads. 当然可以,使用线程。 Here's a server:
这是一个服务器:
import SocketServer
import threading
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "%s wrote:" % self.client_address[0]
print data
socket.sendto(data.upper(), self.client_address)
def serve_thread(host, port):
server = SocketServer.UDPServer((host, port), MyUDPHandler)
server.serve_forever()
threading.Thread(target=serve_thread,args=('localhost', 9999)).start()
threading.Thread(target=serve_thread,args=('localhost', 12345)).start()
It creates a server to listen on 9999 and another to listen on 12345. Here's a sample client you can use for testing this: 它创建了一个服务器来监听9999而另一个服务器监听12345.这是一个示例客户端,您可以用它来测试它:
import socket
import sys
HOST, PORT = "localhost", 12345
data = 'da bomb'
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print "Sent: %s" % data
print "Received: %s" % received
Note: this was taken from the docs of the SocketServer
module, and modified with threads. 注意:这是从
SocketServer
模块的文档中获取的,并使用线程进行修改。
No need to use threads for something like this. 不需要使用线程来做这样的事情。 Consider http://code.google.com/p/pyev/
考虑http://code.google.com/p/pyev/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.