mDNS注册的服务在windows上不总是可发现

2024-04-29 19:43:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在android客户端设备和windows服务器之间建立无线通信。 我使用的服务器是一个python程序,它使用Python zeroconf注册mDNS服务。 一切似乎都很好,但我注意到,在短时间内(通常约一分钟),我的服务将不再被发现。为了减少错误,我尝试了模块github中提供的示例代码,但遇到了相同的问题:

import argparse
import logging
import socket
from time import sleep

from zeroconf import IPVersion, ServiceInfo, Zeroconf

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', action='store_true')
    version_group = parser.add_mutually_exclusive_group()
    version_group.add_argument('--v6', action='store_true')
    version_group.add_argument('--v6-only', action='store_true')
    args = parser.parse_args()

    if args.debug:
        logging.getLogger('zeroconf').setLevel(logging.DEBUG)
    if args.v6:
        ip_version = IPVersion.All
    elif args.v6_only:
        ip_version = IPVersion.V6Only
    else:
        ip_version = IPVersion.V4Only

    desc = {'path': '/~paulsm/'}

    info = ServiceInfo(
        "_http._tcp.local.",
        "Paul's Test Web Site._http._tcp.local.",
        addresses=[socket.inet_aton("127.0.0.1")],
        port=80,
        properties=desc,
        server="ash-2.local.",
    )

    zeroconf = Zeroconf(ip_version=ip_version)
    print("Registration of a service, press Ctrl-C to exit...")
    zeroconf.register_service(info)
    try:
        while True:
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        print("Unregistering...")
        zeroconf.unregister_service(info)
        zeroconf.close()

此外,我尝试编写另一个服务,但这次使用Java使用JmDNS,但有同样的问题,该服务在很短的一段时间内是可发现的,在永久消失之前

主要类别:

public class MainClass {
public static void main(String[] args) {

    NSDService nsdService = new NSDService();
    nsdService.regService();

}

NetworkServiceDiscovery类:

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import java.io.IOException;
import java.net.InetAddress;

public class NSDService {


    public void regService(){
        try {
        // Create a JmDNS instance
        JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
        System.out.println(" Registering service");

        // Register a service
        ServiceInfo serviceInfo = ServiceInfo.create("_http._tcp.local.", "JAVA TEST", 42069, "path=index.html");
        jmdns.registerService(serviceInfo);

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
}

这个问题让我相信这要么是防火墙问题(我不这么认为,我在测试时禁用了防火墙和防病毒),要么是Windows上的问题

在Linux上测试完全相同的python代码并没有引起这样的问题,在我写这篇文章之前,服务器已经运行了2个多小时

有没有办法解决这个问题,最好是使用Python,我不介意使用Windows特定的API调用,但不幸的是,我不能使用Linux环境

编辑: 我发现了一个使用zeroconf.update_service()方法的解决方法,我在一个无限循环中使用它,在一个单独的线程中运行30秒的睡眠时间,到目前为止,它工作得很可靠


Tags: importipaddparserversionlocalloggingservice