Windows在作为服务运行时不接受套接字连接



我正在用Python在Windows 10上编写一个小型应用程序。它应该监听TCP套接字连接并接收一些数据。应用程序不需要任何响应。应用程序必须作为windows服务运行。在调试模式下运行时,它可以完美工作。它接收并处理数据。当作为服务运行(使用pyinstaller和pywin32包(时,不会收到任何数据,也不会发生任何事情。

def sockThread(port: int, interface: str):
global sock 
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((interface, port))
except socket.error as e:
logging.error('could not open socket connection with' + interface + ":" + str(port))
logging.error('error: ' + str(e))
return


logging.info("socket timeout: " + str(sock.gettimeout()))

#run:
while stop==False:
logging.info("socketthread starting, listening on:" + interface + ":" + str(port))
try:
sock.listen(1)
c, addr = sock.accept()
#logging.info("socketthread connection accepted")
except socket.error as e:
logging.error('error while listening to socket:' + str(e))
else:
data = c.recv(2048)
#logging.info("data received: " + str(data))
processStarter.startSubProcess(data)
logging.error("socket thread leaving")

代码使用Raspberry Pi命令行进行测试:netcat -w1 192.168.178.27 60000 <testfile.txt

Windows服务和应用程序的配置有什么不同吗?

找到了";Windows不接受连接":调试器中的服务和应用程序的Windows防火墙规则不同。因此,我的代码中仍然存在一些错误,但现在连接作为服务运行时已被接受。

Windows服务必须有专门注册的端口才能侦听。

命令是:

netsh http add urlacl url=http://+:PORT/

关于add urlacl的更多信息,请点击此处:https://learn.microsoft.com/pl-pl/windows/win32/http/add-urlacl

最新更新