【发布时间】:2020-05-02 22:42:56
【问题描述】:
我有一个 python Twisted 服务器应用程序与旧客户端应用程序接口,并且每个客户端都被分配了一个特定的端口来连接到服务器。所以我已经在服务器上的所有这些端口上设置了监听器,它工作得很好,但是我需要建立一些保护措施来禁止多个客户端连接到同一个服务器端口上。当另一个客户端连接到同一个端口时,客户端应用程序上有太多东西会中断,我现在无法更新该应用程序。我必须忍受它的运作方式。 我知道我可以在 connectionMade() 函数中构建一些逻辑,以查看该端口上是否已经存在某人,如果存在,则关闭这个新连接。但我宁愿有一种方法来拒绝它,所以甚至不允许客户端连接。然后客户端会知道他们犯了一个错误,他们可以改变他们尝试连接的端口。
如果有帮助,这里是我的服务器代码的精简版。
from twisted.internet.protocol import Factory
from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet import task
import time
class MyServerTasks():
def someFunction(msg):
#Do stuff
def someOtherFunction(msg):
#Do other stuff
class MyServer(Protocol):
def __init__(self, users):
self.users = users
self.name = None
def connectionMade(self):
#Depending on which port is connected, go do stuff
def connectionLost(self, reason):
#Update dictionaries and other global info
def dataReceived(self, line):
t = time.strftime('%Y-%m-%d %H:%M:%S')
d = self.transport.getHost()
print("{} Received message from {}:{}...{}".format(t, d.host, d.port, line)) #debug
self.handle_GOTDATA(line)
def handle_GOTDATA(self, msg):
#Parse the received data string and do stuff based on the message.
#For example:
if "99" in msg:
MyServerTasks.someFunction(msg)
class MyServerFactory(Factory):
def __init__(self):
self.users = {} # maps user names to Chat instances
def buildProtocol(self, *args, **kwargs):
protocol = MyServer(self.users)
protocol.factory = self
protocol.factory.clients = []
return protocol
reactor.listenTCP(50010, MyServerFactory())
reactor.listenTCP(50011, MyServerFactory())
reactor.listenTCP(50012, MyServerFactory())
reactor.listenTCP(50013, MyServerFactory())
reactor.run()
【问题讨论】:
标签: python twisted twisted.internet