Python中WebSocket库

tornado

安装

1
pip install tornado

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import uuid

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket

# 所有的客户端
clients = []


class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
self.clientid = str(uuid.uuid4())
print("WebSocket opened:"+self.clientid)
clients.append(self)

def on_message(self, message):
if type(message) == str:
print("Message received: {}".format(message))
self.write_message("You said: " + message)
elif type(message) == bytes:
print("字节类型数据,长度为:", len(message))

def on_close(self):
print("WebSocket closed:"+self.clientid)
clients.remove(self)

def check_origin(self, origin):
return True


app = tornado.web.Application([(r"/ws", WebSocketHandler)])

server = tornado.httpserver.HTTPServer(app)


def start_ws_server():
server.listen(8081)
tornado.ioloop.IOLoop.instance().start()

启动

1
start_ws_server()

多线程启动

1
2
3
4
5
6
7
8
from threading import Thread
from utils.z_ws_server import start_ws_server

def run_ws_server():
start_ws_server()

t = Thread(target=run_ws_server, args=())
t.start()