1

我有一个用 python 2.7 编写的服务器,它执行一个无限循环并处理来自端口 5000 的信息。是否可以在不重新启动服务器的情况下更改此连接端口?例如:服务器在端口 5000 中运行并接收“change_port”选项,服务器模块必须停止在端口 5000 中侦听才能开始在端口 7000 中侦听。我不知道我是否可以像这样操作套接字...谢谢

4

2 回答 2

1

一旦将套接字绑定到地址(接口、端口),它就无法更改。但是,您可以创建一个新套接字(或多个,取决于您的需要)并将其绑定到您的地址(接口、端口)。该代码将根据您使用的传输层协议而有所不同:

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 的客户端相同。

于 2013-07-26T04:51:34.357 回答
1

不,您似乎无法在 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 处理了两个端口。您还应该能够为每个端口定义单独的服务器类。

于 2013-07-26T05:01:21.737 回答