Socket.io

Easy abstraction for sockets with lib for client and NodeJS server

npm install socket.io
npm install socket.io-client
  • Supports JSON, ArrayBuffer, and Blob

  • Highly robust: Autoreconnects; starts with longpolling before upgrading to Websockets if supported

General Usage

IO

Emit sends event to all connect clients

//server
io.emit('some event', { someProperty: 'some value', otherProperty: 'other value' });
//client
socket.on('some event', (data) => { 
	//....
});

Rooms allow you to create seperate channels

Socket

  • .id - each socket by default joins a room identified by this random id

Emit event to specific socket

Only server-side, broadcast sends message to everyone except socket that starts it

Namespace

Setup custom namespace's server-side

Then connect to it client side

Room

Within each namespace, you can have many rooms that can be joined or left

To leave a channel you call leave in the same fashion as join. Both methods are asynchronous and accept a callback argument.

Server/Client Usage

Server

Setuping up with express generator's bin/www is a little tricky

Socket.js

Require this file to access the right fts in the routes

bin/www

Client

PM

Client-side (sending message)

where to refers to the id to send a private message to and msg is the content.

Client-side (receiving message)

where chatLog is a div displaying the chat messages.

Server-side

Extra

Authentication can be done by appending user token to query string

Or socketio-auth

Last updated