Web socket pluggable application that uses a specific JSON format to simulate express fashion request response architecture using websockets. Runs on same port as of the express app (if any).
Type npm install angry-websocket-app
or npm install angry-websocket-app --save
in command line to install the package in current directory.
File: "my_ctrl.js"
function someFunc(msg, reply, disconnect){
var a = msg.abc;
var b = msg.something;
reply( 'xyz' + a + b );
}
function someOtherFunc(msg, reply, disconnect){
var a = msg.abc;
var b = msg.something;
/*
to broadcast message to all connected users
pass true as second argument
*/
reply( 'xyz' + a + b, true );
}
module.exports = {
someFunc: someFunc,
someOtherFunc: someOtherFunc
};
File: "my_socket_app.js"
var socketApp = require('angry-websocket-app');
var controller = require('./my_ctrl.js');
socketApp.onKey('any-string', controller.someFunc);
socketApp.onKey('broadcast-this', controller.someOtherFunc);
...
...
...
module.exports = socketApp.init;
File: "index.js"
var mySocketApp = require('./my_socket_app.js');
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
// initialize socket app with http server
mySocketApp(server, '/somepath');
server.listen(3000, ()=>{
console.log("listening on port 3000");
});
Client side js
var socket = new WebSocket('ws://localhost:3030/somepath');
socket.onopen = function(){
var testMsg = {
// key should be present in msg
key: 'broadcast-this',
// body should contain actual msg
// it can be string or object or anything
body: {
a: 'asdf',
b: 'bjsad'
}
};
// its required to convert msg to JSON string
testMsg = JSON.stringify(testMsg);
socket.send(testMsg);
};