Skip to content

Instantly share code, notes, and snippets.

@ericremoreynolds
Last active February 25, 2024 21:55
Show Gist options
  • Save ericremoreynolds/dbea9361a97179379f3b to your computer and use it in GitHub Desktop.
Save ericremoreynolds/dbea9361a97179379f3b to your computer and use it in GitHub Desktop.
Flask-socket.io emit to specific clients
<html>
<body>
<h1>I feel lonely</h1>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('connected');
});
socket.on('message', function(data) {
$('h1').text(data)
});
</script>
</body>
</html>
from flask import Flask, request
from flask.ext.socketio import SocketIO
app = Flask(__name__, static_folder='')
io = SocketIO(app)
clients = []
@app.route('/')
def index():
return app.send_static_file('client.html')
@io.on('connected')
def connected():
print "%s connected" % (request.namespace.socket.sessid)
clients.append(request.namespace)
@io.on('disconnect')
def disconnect():
print "%s disconnected" % (request.namespace.socket.sessid)
clients.remove(request.namespace)
def hello_to_random_client():
import random
from datetime import datetime
if clients:
k = random.randint(0, len(clients)-1)
print "Saying hello to %s" % (clients[k].socket.sessid)
clients[k].emit('message', "Hello at %s" % (datetime.now()))
if __name__ == '__main__':
import thread, time
thread.start_new_thread(lambda: io.run(app), ())
while True:
time.sleep(1)
hello_to_random_client()
@charles-dr
Copy link

I tried this and works for me:

io.emit('message', "Hello at %s" % (datetime.now()), room=clients[k])

This clients[k] is the ID of the conection... On cliente is socket.id and in the server is request.sid (This one you need to import from flask import request)

I dont tried if puttin an array in room will send to all clients in there...

Thanks, @juniordnts.
The above code worked for me finally, and here is my code.
Hope it helps others save time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment