我有一个用python 2.7编写的服务器,它执行无限循环并处理来自端口5000的信息。是否可以在不重新启动服务器的情况下更改此连接端口? 例如:服务器在端口5000中运行并接收'change_port'选项,服务器模块必须停止在端口5000中侦听以开始侦听端口7000.我不知道我是否可以像这样操作套接字...感谢
答案 0 :(得分:0)
将套接字绑定到地址(接口,端口)后,无法更改。但是,您可以创建一个新套接字(或多个,取决于您的需要)并将其绑定到您的地址(接口,端口)。 代码将根据您使用的传输层协议而有所不同:
TCP:
# 1) Create first socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind(('0.0.0.0',5000))
# 2) Create second socket
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.bind(('0.0.0.0',7000))
# 3) Wait for a connection on the first socket
s1.listen(5)
sc, address = s1.accept()
# 4) Once a connection has been established...
# send, recv, process data
# until you need the next socket
# 5) Open connection on second socket
s2.listen(1)
sc2, address2 = s2.accept()
# now it probably a good time to tell the client (via s1) that s2 is ready
# client connects to s2
你去了
UDP(几乎相同):
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s1.bind(('0.0.0.0',5000))
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2.bind(('0.0.0.0',7000))
data, addr = s1.recvfrom(256)
s1.sendto("s2 ready",addr)
data2, addr2 = s2.recvfrom(256)
简化,但这就是真的。 您可以考虑验证来自s1的客户端地址与连接到s2的客户端的地址相同。
答案 1 :(得分:0)
不,似乎你已经绑定时无法运行socket.bind()方法。但是,我有一个可以与Asyncore模块一起使用的解决方案。
继承我的服务器:
import asyncore
import socket
class EchoHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(8192)
if data:
print "Recieved Data: ", data, ". This server address:", self.getsockname()
class EchoServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
handler = EchoHandler(sock)
server = EchoServer('localhost', 56787)
server = EchoServer('localhost', 56788)
asyncore.loop()
以下是我的客户:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 56787))
data = ""
while data.upper() != "Q":
data = raw_input("Enter something to send to the server")
s.send(data)
s.close()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 56788))
data = ""
while data.upper() != "Q":
data = raw_input("Enter something to send to the server")
s.send(data)
s.close()
这很好用,python处理了两个端口。您还应该能够为每个端口定义单独的服务器类。