SockJS is a Javascript library that provides a
WebSocket-like object, allows you to create real-time, low-latency, full duplex
and cross-domain communication. SockJS tries to use WebSocket in the background
if the browser supports so the syntax is very similar to WebSocket object.
This post demonstrate a simple chat example using SockJS with NodeJS server. For
other kinds of server, you can find it on the SockJS Github page
https://github.com/sockjs.
SockJS include 2 parts, client-side SockJS and server-side SockJS. You need both
for your application to run properly.
Server-side SockJS
The SockJS server will listen for all connection on port 9999 (you can change to
whatever you want). Every time a client send a chat message to the server, it
will broadcast to all other clients.
Create a new folder sockjs-server for your SockJS server. Create a file name
server.js. First, you need to load all the required dependencies. Add this to
your server.js file.
You also need an object to hold a list of all connected clients
This function is used to broadcast message to all clients
Create a sockjs server like this
Create an http server and integrate sockjs inside that, listening on port 9999.
The client will need to connect to http://localhost:9999/echo (as specifiec in
the prefix configuration).
You can download the file server.js from this
link.
Open Terminal, change to sockjs-server folder and issue these commands to
run the server
Client-side SockJS
Create another folder sockjs-client for client-side chat application. Make a
new file index.html with the content like this
Create another index.js file for the JS code. First, you need to create a
connection to http://localhost:9999/echo.
When receive message from the server, show it in the textarea
This function is for handling Send button click event