-
-
Save kingspp/5a1943daa415f4114f92bac8da1dc979 to your computer and use it in GitHub Desktop.
Flask-socket.io emit to specific clients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment