From 20e78c095b8ab450d1821ad5145226371bac054e Mon Sep 17 00:00:00 2001 From: iou1name Date: Thu, 14 Jun 2018 18:49:01 -0400 Subject: [PATCH] added rooms, clients can talk to each other --- anonkun.py | 15 ++++++++++----- templates/index.html | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/anonkun.py b/anonkun.py index 811b3d6..a611351 100644 --- a/anonkun.py +++ b/anonkun.py @@ -7,7 +7,7 @@ import time from flask import Flask, session, request, abort, redirect, url_for, g, \ render_template -from flask_socketio import SocketIO, emit +from flask_socketio import SocketIO, emit, join_room class ReverseProxied(object): """ @@ -50,24 +50,29 @@ app.config['SECRET_KEY'] = 'secret!' app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 socketio = SocketIO(app) -@socketio.on('joined', namespace='/chat') -def joined(message): +@socketio.on('joined', namespace="/chat") +def joined(data): """ Sent by clients when they enter a room. """ + room = data["room"] + join_room(room) print("Client connected.") -@socketio.on('text', namespace='/chat') +@socketio.on('message', namespace="/chat") def text(data): """ Sent by a client when the user entered a new message. """ + room = data["room"] + message = data["message"] name = data["name"] date = int(time.time()) data["date"] = date - emit('message', data) + + emit('message', data, room=room) @app.template_filter("strftime") diff --git a/templates/index.html b/templates/index.html index 9499a9c..5b8f033 100644 --- a/templates/index.html +++ b/templates/index.html @@ -11,7 +11,7 @@ socket = io.connect('https://' + document.domain + ':' + location.port + '/chat'); socket.on('connect', function() { - socket.emit('joined', {}); + socket.emit('joined', {room: 'index'}); }); socket.on('message', function(data) { date = new Date(data.date * 1000); @@ -30,7 +30,7 @@ if (event.key == 'Enter') { text = document.getElementById('text').value; document.getElementById('text').value = ''; - socket.emit('text', {message: text, name: 'Anonymous'}); + socket.emit('message', {message: text, name: 'Anonymous', room: 'index'}); } }); }, 100 );