我想将websocket服务器作为Windows服务运行。 通过从Python角落复制和修改代码以创建服务,我能够创建一个简单的echo服务器:
https://www.thepythoncorner.com/2018/08/how-to-create-a-windows-service-in-python/
我在这里使用了代码:
https://websockets.readthedocs.io/en/stable/intro.html
创建websocket回显服务器。
我可以安装该服务
python create_service.py install
启动服务:
python create_service.py start
套接字服务器正常运行。但是当我尝试像这样停止服务时:
python create_service.py stop
和:
python create_service.py remove
我得到确认
stopping service
和
Service removed
在控制台中。但是在处于状态的任务管理器中,它说:停止挂起。 而且websocket仍在响应客户端。因此,显然挂起了。
最终我可以使用taskkill杀死它,但是一定有问题。 我只能通过websocket看到此行为。像原始示例中一样的其他代码也可以启动和停止。所以我想这与python的asyncio有关。 有没有人对此问题有经验,或者对这里发生的事情有更深入的了解?
基类(service_base.py)的复制代码:
'''
SMWinservice
by Davide Mastromatteo
Base class to create winservice in Python
-----------------------------------------
Instructions:
1. Just create a new class that inherits from this base class
2. Define into the new class the variables
_svc_name_ = "nameOfWinservice"
_svc_display_name_ = "name of the Winservice that will be displayed in scm"
_svc_description_ = "description of the Winservice that will be displayed in scm"
3. Override the three main methods:
def start(self) : if you need to do something at the service initialization.
A good idea is to put here the inizialization of the running condition
def stop(self) : if you need to do something just before the service is stopped.
A good idea is to put here the invalidation of the running condition
def main(self) : your actual run loop. Just create a loop based on your running condition
4. Define the entry point of your module calling the method "parse_command_line" of the new class
5. Enjoy
'''
import socket
import win32serviceutil
import servicemanager
import win32event
import win32service
class SMWinservice(win32serviceutil.ServiceFramework):
'''Base class to create winservice in Python'''
_svc_name_ = 'pythonService'
_svc_display_name_ = 'Python Service'
_svc_description_ = 'Python Service Description'
@classmethod
def parse_command_line(cls):
'''
ClassMethod to parse the command line
'''
win32serviceutil.HandleCommandLine(cls)
def __init__(self,args):
'''
Constructor of the winservice
'''
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
'''
Called when the service is asked to stop
'''
self.stop()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
'''
Called when the service is asked to start
'''
self.start()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_,''))
self.main()
def start(self):
'''
Override to add logic before the start
eg. running condition
'''
pass
def stop(self):
'''
Override to add logic before the stop
eg. invalidating running condition
'''
pass
def main(self):
'''
Main class to be ovverridden to add logic
'''
pass
# entry point of the module: copy and paste into the new module
# ensuring you are calling the "parse_command_line" of the new created class
if __name__ == '__main__':
SMWinservice.parse_command_line()
我修改后的服务创建者(create_service.py):
import time
import random
from pathlib import Path
from service_base import SMWinservice
import asyncio
import websockets
async def hello(websocket,path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
class MyService(SMWinservice):
_svc_name_ = "_MyService"
_svc_display_name_ = "Winservice Example"
_svc_description_ = "Simple example for a service"
def start(self):
self.isrunning = True
def stop(self):
self.isrunning = False
def main(self):
start_server = websockets.serve(hello,"localhost",8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
if __name__ == '__main__':
MyService.parse_command_line()
websocket客户端(client.py):
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())