MDNSBrowseHandler示例代码
时间: 2023-07-09 19:40:26 浏览: 119
以下是使用MDNSBrowseHandler的示例代码:
```python
import asyncio
import logging
import time
from zeroconf import ServiceBrowser, Zeroconf
from zeroconf import ServiceInfo, IPVersion
_LOGGER = logging.getLogger(__name__)
class MyListener:
def remove_service(self, zeroconf, type, name):
_LOGGER.info("Service %s removed", name)
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
if info:
_LOGGER.info("Service %s added, service info: %s", name, info)
else:
_LOGGER.warning("Service %s added, but service info is None", name)
async def browse_services(zc: Zeroconf, typ: str, listener: MyListener):
browser = ServiceBrowser(zc, typ, listener)
while True:
await asyncio.sleep(0.5)
async def main():
zc = Zeroconf(ip_version=IPVersion.V4Only)
listener = MyListener()
service_type = "_http._tcp.local."
task = asyncio.create_task(browse_services(zc, service_type, listener))
try:
while True:
await asyncio.sleep(1)
finally:
task.cancel()
await task
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
```
这个示例代码可以使用zeroconf库来发现局域网内的HTTP服务。在这个示例中,我们定义了一个`MyListener`类,它实现了`remove_service`和`add_service`方法,在服务被添加和删除时调用。然后我们定义了一个`browse_services`的协程,使用`ServiceBrowser`类来浏览服务。最后,在`main`函数中,我们创建了一个Zeroconf实例,然后启动了一个无限循环的协程来等待服务的发现结果。
阅读全文