基于mDNS通告服务
使用 https://github.com/python-zeroconf/python-zeroconf
pip install zeroconf
发现服务
from zeroconf import ServiceBrowser, ServiceListener, Zeroconf
class MyListener(ServiceListener):
def update_service(self, zc: Zeroconf, type_: str, name: str) -> None:
print(f"Service {name} updated")
def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None:
print(f"Service {name} removed")
def add_service(self, zc: Zeroconf, type_: str, name: str) -> None:
info = zc.get_service_info(type_, name)
print(f"Service {name} added, service info: {info}")
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
发布服务
from zeroconf import ServiceInfo, Zeroconf
info = ServiceInfo(
"_http._tcp.local.",
"My Service Name._http._tcp.local.",
addresses=[socket.inet_aton("192.168.1.123")],
port=3000,
properties={"foo": "bar"},
server="ash-2.local.",
)
zeroconf = Zeroconf()
zeroconf.register_service(info)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.unregister_service(info)
zeroconf.close()