Skip to content

Instantly share code, notes, and snippets.

@gtindo
Last active December 7, 2019 16:04
Show Gist options
  • Save gtindo/d89e6b24c2a0b55be3d061511c2bc9ce to your computer and use it in GitHub Desktop.
Save gtindo/d89e6b24c2a0b55be3d061511c2bc9ce to your computer and use it in GitHub Desktop.
/*********************************
* Server side of implementation
**********************************/
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get("/", (req, res) => {
res.render("client.ejs");
});
io.on('connection', (socket) => {
socket.on('register', (message) => {
data = JSON.parse(message);
clientId = data["clientId"];
socket.join(clientId); // All connections of a client pushed in a room
console.log(clientId);
//Broadcast to all connection of the same client
io.to(clientId).emit("registration", "New connection registered");
});
});
app.get("/http-socket/:clientId", (req, res) => {
//receive http request and send response to all connection registered with clientId
//Same process can be done with an AMQP consumer context
var clientId = req.params.clientId;
try{
io.to(clientId).emit("http", "Message sent with http context"); //broadcast to all connections
return res.status(200).json({status: "success"})
}catch(e){
return res.status(500).json({status: "error"});
}
})
http.listen(3000, () => {
console.log('listening on *:3000');
});
/*********************************
* Client side of implementation
**********************************/
var socket = io();
var data = JSON.stringify({
clientId: "Client_21"
});
socket.emit('register', data);
socket.on("registration", (message) => {
console.log(message);
});
socket.on("http", (message) => {
console.log(message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment