我使用 Twisted 创建了一个带有自定义协议(protocol)的服务器,我的客户端连接到服务器的特定端口(例如端口 1234)。我希望基于某种网页为服务器创建一个控制界面。到目前为止,我的研究表明 Nevow 是受欢迎的选择,但我只需要一些非常简单的东西。
例如,每次浏览器访问端口 8080 上的 hello world 页面时,我都会向连接在 1234 上的客户端发送一条消息。
我对如何将这两个连接在一起感到有点困惑。我假设我需要从 HelloResource.render_GET 调用 Server.message ?
from twisted.internet import protocol, reactor
from twisted.web.resource import Resource
class Server(protocol.Protocol):
def dataReceived(self, data):
#do something on the server side
def message(self)
#send message to clients
class HelloResource(Resource):
isLeaf = True
def render_GET(self,request):
return "<html>Hello, world!</html>"
factory = protocol.Factory()
factory.protocol = Server
reactor.listenTCP(1234, factory)
reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()
最佳答案
这与 a question answered in the Twisted FAQ 非常相似.
本质上,您需要让您的工厂创建的协议(protocol)实例可供构成您的网络服务器的资源访问。
一个简单的方法是让你的工厂保存一个协议(protocol)实例列表(如果你还没有阅读buildProtocol
),然后将工厂实例传递给你的HelloResource
初始化器,然后让该初始化器将工厂保存为 HelloResource
实例的属性。
这将 HelloResource
访问协议(protocol)实例列表 - 通过它现在引用的工厂对象 - 然后它可以迭代,例如,调用每个协议(protocol)的方法实例。
关于python - 从 Web 界面控制基于 Twisted 的服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15146564/