Skip to content

Commit a87bcfa

Browse files
Update websocket example
1 parent 93b9c34 commit a87bcfa

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

examples/ws_example.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1+
import os
12
import sys
23
import json
34
import uuid
45
import asyncio
56
import base64
67
import logging
8+
import signal
79
from typing import Optional
810

911
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s')
1012
logger = logging.getLogger(__name__)
1113

1214
from pymixin.mixin_ws_api import MixinWSApi, MessageView, Category, MessageStatus
1315

16+
print(os.getpid())
17+
1418
bot_config = None
1519

1620
with open(sys.argv[1]) as f:
@@ -22,6 +26,25 @@ class MixinBot(MixinWSApi):
2226
def __init__(self):
2327
super().__init__(bot_config, on_message=self.on_message)
2428

29+
def init(self):
30+
loop = asyncio.get_running_loop()
31+
loop.add_signal_handler(signal.SIGINT, lambda: asyncio.create_task(self.handle_signal(signal.SIGINT)))
32+
loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(self.handle_signal(signal.SIGTERM)))
33+
34+
async def handle_signal(self, signum):
35+
logger.info("+++++++handle signal: %s", signum)
36+
loop = asyncio.get_running_loop()
37+
for task in asyncio.all_tasks(loop):
38+
task.cancel()
39+
40+
async def run(self):
41+
self.init()
42+
try:
43+
await super().run()
44+
except asyncio.CancelledError:
45+
await self.ws.close()
46+
print('CancelledError')
47+
2548
async def on_message(self, id: str, action: str, msg: Optional[MessageView]) -> None:
2649
logger.info("on_message: %s %s %s", id, action, msg)
2750

@@ -62,6 +85,7 @@ async def on_message(self, id: str, action: str, msg: Optional[MessageView]) ->
6285
bot = MixinBot()
6386

6487
async def start():
88+
bot.init()
6589
await bot.run()
6690

6791
if __name__ == '__main__':

0 commit comments

Comments
 (0)