最重要的是,我的问题非常类似于以下内容:Cannot access Python server running as Windows service。我尝试了解决方案,但它没有解决我的问题。
我可以使用Python Socket Tutorial连接客户端和服务器:
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
它就像一个魅力,然后我编写了以下Windows服务:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
import sys
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "PySvc"
_svc_display_name_ = "PySvc"
_svc_description_ = "PySvc"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
logging.basicConfig(filename='C:/test.log',
level =logging.DEBUG,
format ='%(asctime)s %(message)s',
filemode='w')
rc = None
self.HOST = '' # Symbolic name meaning the local host
self.PORT = 50007 # Arbitrary non-privileged port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((self.HOST, self.PORT))
logging.debug("BIND")
self.s.listen(1)
logging.debug("LISTENED")
self.conn, self.addr = self.s.accept()
logging.debug("ACCEPT")
logging.debug("connected to " + str(self.addr))
self.s.setblocking(1)
logging.debug("set blocking")
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
但服务从未接受过这种联系。日志包含:
2018-03-19 16:37:48,967 BIND
2018-03-19 16:37:48,967 LISTENED
如果我使用netstat:
NETSTAT -an | find /i "listening"
我找到以下行,显示服务器正在侦听:
TCP 0.0.0.0:50007 0.0.0.0:0 LISTENING
有人可以解释一下为什么它不起作用?