forked from sirkaiserkai/Flask-SocketIO-Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
83 lines (57 loc) · 1.82 KB
/
Copy pathapp.py
File metadata and controls
83 lines (57 loc) · 1.82 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from gevent import monkey
monkey.patch_all()
from flask import Flask, render_template, session, request
from flask.ext.socketio import SocketIO, emit, disconnect
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
usernames = {}
number_of_users = 0
@app.route('/')
def index():
return render_template('index.html')
# When the client emits 'connection', this listens and executes
@socketio.on('connection', namespace='/chat')
def user_connected():
print 'User connected'
# When the client emits 'new message', this listens and executes
@socketio.on('new message', namespace='/chat')
def new_message(data):
emit('new message',
{ 'username' : session['username'],
'message': data }, broadcast=True )
# When client emits 'add user' this listens and executes
@socketio.on('add user', namespace='/chat')
def add_user(data):
global usernames
global number_of_users
session['username'] = data
usernames[data] = session['username']
number_of_users += 1;
emit('login', { 'numUsers' : number_of_users })
emit('user joined', { 'username' : session['username'], 'numUsers': number_of_users }, broadcast=True)
@socketio.on('typing', namespace='/chat')
def typing_response():
try:
emit('typing', { 'username' : session['username'] }, broadcast=True )
except:
pass
@socketio.on('stop typing', namespace='/chat')
def stop_typing():
try:
emit('stop typing', { 'username' : session['username'] }, broadcast = True)
except:
pass
@socketio.on('disconnect', namespace='/chat')
def disconnect():
global usernames
global number_of_users
try:
del usernames[session['username']]
number_of_users -= 1
emit('user left', { 'username' : session['username'], 'numUsers' : number_of_users}, broadcast=True)
except:
pass
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')