Last active
September 9, 2017 15:54
-
-
Save ejhari/605fe079d75d0315cf989fd6603450ab to your computer and use it in GitHub Desktop.
SocketIO Setup
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
/* | |
* Javascript SocketIO Client v1.4.5 | |
* | |
*/ | |
// Setup SocketIO to connect to server at | |
// given path on given namespace. | |
var socket = io(window.SERVER_URL + '/karma', { | |
query: 'email='+window.email, | |
path: '/api/socket.io' | |
}); | |
socket.on('connect', function() { | |
console.log('socket connected'); | |
}); | |
socket.on('disconnect', function() { | |
console.log('socket disconnected'); | |
}); | |
socket.on('helloworld', function (data) { | |
console.log('helloworld:', data); | |
}); |
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
# | |
# Python SocketIO Client | |
# | |
# socketIO-client==0.7.0 | |
# | |
import urlparse | |
import hostname | |
from socketIO_client import SocketIO, namespaces, BaseNamespace | |
import config | |
class SocketIOMessagesNamespace(BaseNamespace): | |
""" | |
Handles SocketIO messages. | |
""" | |
@classmethod | |
def on_connect(self): | |
logger.debug('Connection established.') | |
@classmethod | |
def on_disconnect(self): | |
logger.error('Disconnected.') | |
@classmethod | |
def on_helloworld(self, *args): | |
payload = args[0] | |
logger.debug('On helloworld: %s', str(payload)) | |
def setup_socket_io(): | |
"""Sets up SocketIO connection.""" | |
socket_io_resource = '/api/socket.io' | |
url_parsed = urlparse.urlparse(config.SERVER_URL) | |
socketIO = SocketIO( | |
url_parsed.hostname, | |
url_parsed.port, | |
namespaces.SocketIONamespace, | |
True, # Block until connection is established | |
('xhr-polling', 'websocket'), | |
socket_io_resource.strip('/'), | |
params={ 'email': email, 'hostname': socket.gethostname() }, | |
#headers={'Authorization': 'Basic ' + b64encode('username:password')}, | |
#cookies={'a': 'aaa'} | |
) | |
# Setup event listeners. | |
socketIO.on('helloworld', SocketIOMessagesNamespace.on_helloworld) | |
# Setup namespaces. | |
karma_ns = socketIO.define(SocketIOMessagesNamespace, '/karma') | |
# Emit events. | |
#karma_ns.emit('helloworld', {'hello': 'world'}) | |
return socketIO | |
# Setup SocketIO. | |
logger.info('Setting up SocketIO.') | |
socketIO = setup_socket_io() | |
# Listen for events. | |
siom = threading.Thread( | |
name='socketio_messages', target=socketIO.wait | |
) | |
siom.daemon = True | |
siom.start() |
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
/* | |
* NodeJS SocketIO Server v1.4.5 | |
* | |
* "socket.io": "^1.4.8" | |
* "socket.io-redis": "^1.0.0" | |
*/ | |
var http = require('http'); | |
var express = require('express'); | |
var redis_server = require('redis'); | |
var socket_io = require('socket.io'); | |
var socket_io_redis = require('socket.io-redis'); | |
var socketio_pub_client = redis.createClient(port, host, { return_buffers: true, db: 0 }); | |
var socketio_sub_client = redis.createClient(port, host, { return_buffers: true, db: 0 }); | |
var redis = { | |
host: host, | |
port: port, | |
clients: { | |
socketio_pub_client: socketio_pub_client, | |
socketio_sub_client: socketio_sub_client | |
} | |
}; | |
var app = express(); | |
var server = http.createServer(app); | |
var io = null; | |
function setupIO(logger, redis, server) { | |
// Setup SocketIO. | |
io = socket_io(server, { path: '/api/socket.io' }); | |
// Configure SocketIO to use Redis store. | |
var io_adapter = socket_io_redis({ | |
key: 'helloworld', | |
host: redis.host, | |
port: redis.port, | |
pubClient: redis.clients.socketio_pub_client, | |
subClient: redis.clients.socketio_sub_client | |
}); | |
io.adapter(io_adapter); | |
// Define SocketIO namespaces. | |
io | |
.of('/karma') | |
.on('connection', function(socket) { | |
logger.info('Socket connected.'); | |
// Join the user's "room" identified by his/her email. | |
var email = socket.handshake.query.email; | |
if (!email) { | |
logger.error('Unrecognized socket! Disconnecting.'); | |
socket.disconnect(); | |
} else { | |
var email = socket.handshake.query.email; | |
var hostname = socket.handshake.query.hostname; | |
logger.debug('Joining room:', email, hostname); | |
socket.join(email); | |
} | |
}) | |
.on('disconnect', function() { | |
logger.info('Socket disconnected.'); | |
}); | |
} | |
function getIO() { | |
return io; | |
} | |
// REF: http://stackoverflow.com/questions/24154480/how-to-update-socket-object-for-all-clients-in-room-socket-io/25028902#25028902 | |
function getSocketsByRoom(room) { | |
var clients = io.sockets.adapter.rooms[room].sockets; | |
//to get the number of clients | |
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0; | |
for (var clientId in clients ) { | |
//this is the socket of each client in the room. | |
var clientSocket = io.sockets.connected[clientId]; | |
//you can do whatever you need with this | |
clientSocket.emit('helloworld', payload); | |
} | |
} | |
/*module.exports = { | |
setupIO: setupIO, | |
getIO: getIO | |
}*/ | |
var room = 'lounge'; | |
var payload = { hello: 'world' }; | |
// REF: http://stackoverflow.com/questions/20441589/nodjs-how-to-broadcast-message-to-namespace-with-room | |
io | |
.of('/karma') | |
.to(room).emit('helloworld', payload); |
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
import socketio | |
import eventlet | |
import eventlet.wsgi | |
from flask import Flask, render_template | |
sio = socketio.Server() | |
app = Flask(__name__) | |
@app.route('/') | |
def index(): | |
"""Serve the client-side application.""" | |
return render_template('index.html') | |
@sio.on('connect', namespace='/karma') | |
def connect(sid, environ): | |
print("connect ", sid) | |
@sio.on('helloworld', namespace='/karma') | |
def message(sid, data): | |
print("message ", data) | |
sio.emit('helloworld', data, room=sid) | |
@sio.on('disconnect', namespace='/karma') | |
def disconnect(sid): | |
print('disconnect ', sid) | |
if __name__ == '__main__': | |
socketio_path='/api/socket.io' | |
# wrap Flask application with engineio's middleware | |
app = socketio.Middleware(sio, socketio_path=socketio_path.strip('/')) | |
# deploy as an eventlet WSGI server | |
eventlet.wsgi.server(eventlet.listen((host, port)), app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment