几个客户端一连接 cpu 就飙升到最高,且客户端断开也不降,
求助代码有啥问题,或者有什么别的 websocket 方案么,
下面是代码
from abc import ABC
from tornado import websocket, web, ioloop, httpserver, gen
from tornado.options import define, options
define("port", default=9040, help="run on the given port", type=int)
class WebSocketHandler(websocket.WebSocketHandler, ABC):
# CORS
def check_origin(self, origin):
return True
def open(self):
self.write_message({'code': 0, 'message': '连接成功'})
async def on_message(self, message):
user = self.get_argument('user', '')
if not user:
await self.write_message({'code': 411, 'message': '缺少用户 id'})
else:
while True:
try:
await self.write_message({'code': 0, 'user': user})
await gen.sleep(3)
except websocket.WebSocketClosedError:
self.on_close()
def on_close(self):
pass
class HealthyCheckHandler(web.RequestHandler, ABC):
def get(self):
self.write("Hello, world")
def make_app():
return web.Application([
("/v1/ws/message", WebSocketHandler),
("/v1/ws/healthycheck", HealthyCheckHandler)
])
def main():
ws_app = make_app()
options.parse_command_line()
server = httpserver.HTTPServer(ws_app)
server.listen(options.port)
ioloop.IOLoop.current().start()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
ioloop.IOLoop.current().stop()
ioloop.IOLoop.current().close(True)
1
tsbx 2019-09-18 11:12:58 +08:00
不知道 楼主 用的系统是什么呢?还有 tornado 的版本呢?
|
2
robot1 2019-09-18 11:22:21 +08:00
twisted 啊 比 tornado 性能要高,易理解
|
3
robot1 2019-09-18 11:22:35 +08:00
twisted + autobahn
|
5
linw1995 2019-09-18 11:41:02 +08:00 1
except websocket.WebSocketClosedError:
self.on_close() 这个后面要补个 return 或者 break 啊 |
6
vissssa OP @linw1995 #5 解决了 cpu 高的问题,但是为什么会这样呢,直接进了 WebSocketClosedError 中去了 这里加了 break 还需要 close()吗
|
7
justfly 2019-09-18 11:50:18 +08:00
while 死循环了,跟框架没关系
|
8
Hstar 2019-09-18 12:12:25 +08:00
因为你的代码一直在 报错-捕捉-pass
|
9
skymei 2019-09-18 12:20:57 +08:00
```python
while True: try: await self.write_message({'code': 0, 'user': user}) await gen.sleep(3) except websocket.WebSocketClosedError: self.on_close() ``` |