angry-websocket-app

1.0.1 • Public • Published

angry-websocket-app


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).

Installation

Type npm install angry-websocket-app or npm install angry-websocket-app --save in command line to install the package in current directory.

Usage

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);
};

Readme

Keywords

none

Package Sidebar

Install

npm i angry-websocket-app

Weekly Downloads

0

Version

1.0.1

License

MIT

Last publish

Collaborators

  • theangryloop