如何解决具有并行作业的扭曲 UDP 多播服务器
我是 Twisted 的新手,我也在学习如何实现一个简单的 UDP 多播服务器的教程。服务器运行良好,但我似乎无法理解实现服务器端作业和 Twisted UDP 设计的最佳方法是什么?
例如:假设服务器有一个从数据库中获取数据的工作,而这个工作并不是真正由传入的数据报包驱动,而是有自己的调度机制。我应该在应用程序上实例化一个新线程吗? Twisted 是否有一种很好的方式将这些东西结合在一起?
UDP 服务器的代码片段是:
# twisted packages
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import threads
# my own files
from network.handler import handle_incoming_package
from constants import MULTICAST_IP_GROUP,SERVER_LISTENING_PORT
class MulticastServer(DatagramProtocol):
def startProtocol(self):
"""
Called after protocol has started listening.
"""
# Set the TTL>1 so multicast will cross router hops:
self.transport.setTTL(5)
# Join a specific multicast group:
self.transport.joinGroup(MULTICAST_IP_GROUP)
# send a message to everyone in the group
self.transport.write(b'Multicast Service Ping',(MULTICAST_IP_GROUP,SERVER_LISTENING_PORT))
'''
address: (host,port)
'''
def datagramReceived(self,datagram,address):
print(f"Datagram {repr(datagram)} received from {repr(address)}")
threads.deferToThread(handle_incoming_package,datagram)
if datagram == b"Client: Ping" or datagram == "Client: Ping":
# Rather than replying to the group multicast address,we send the
# reply directly (unicast) to the originating port:
self.transport.write(b"Server: Pong",address)
入口点:
from twisted.internet import reactor
from network.multicast import MulticastServer
from constants import SERVER_LISTENING_PORT
def main():
reactor.listenMulticast(SERVER_LISTENING_PORT,MulticastServer(),listenMultiple=True)
reactor.run()
if __name__ == "__main__":
main()
```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。