-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebsocket_route.py
47 lines (36 loc) · 1.02 KB
/
websocket_route.py
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
41
42
43
44
45
46
47
from flask import session
from flask_socketio import (
emit,
join_room,
leave_room,
SocketIO,
)
# 创建websocket对象
socketio = SocketIO()
@socketio.on('connect', namespace='/chat')
def test_connect():
print('Client connected')
@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
print('Client disconnected')
@socketio.on('join', namespace='/chat')
def on_join(data):
username = session.get('name')
room = data
join_room(room)
session['room'] = room
data = username + ' has entered the room.'
emit('status', data, room=room)
@socketio.on('leave', namespace='/chat')
def on_leave(data):
username = session.get('name')
room = session.get('room')
leave_room(room)
data = username + ' has lefted the room.'
emit('status', data, room=room)
@socketio.on('send', namespace='/chat')
def on_send(data):
username = session.get('name')
room = session.get('room')
message = '{}: {}'.format(username, data)
emit('message', message, room=room)