Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, November 11, 2019

Using websocket on client and on server side

For many web applications, REST calls are the standard for client-server communication.
However, REST calls do not suit a more complex interactions, for example:

  • The server should notify the client when something changes
  • Using sticky sessions in a load balanced environment (Notice that you can use ingress to enforce stickiness, but forces usage of ingress, see this article)

A standard method to handle this requirement is using a web sockets.


The client creates a socket to the server, and leaves it open. Then, the server and the client can send frames over the socket whenever they need. This has performance implications, as the server must maintain an open socket for each running client.

Implementing web sockets in javascript is easy. Let review the implementation on the client side and on the server side. First, install the web socket library:


npm install --save socket.io-client


The Client Side

On the main client page, import the web socket library

const socketIo = require('socket.io-client')

Next, upon page load, or any other event that require the web socket establishment, connect to the server

const webSocket = socketIo.connect('http://my-server', {transports: ['websocket']})

To send a frame from the client over the web socket to the server, we specify the frame type, and the data

webSocket.emit('type1',{name:'Alice'})

And the last thing to do, is to handle the events triggered by the web socket. These include both error handling, and frames received from the server

webSocket.on('error', (e) => {
 console.error(e)
})
webSocket.on('disconnect', () => {
 console.log('web socket is disconnected')
})
webSocket.on('connect', () => {
 console.log('web socket is connected')
})
webSocket.on('type2', (dataFromServer) => {
 console.log('got type2 frame from the server', dataFromServer)
})


The Server Side

Create web socket listener on the server side

import socketIo from 'socket.io'
import express from 'express'
import http from 'http'

const app = express()
const server = http.Server(app)
const webSocketServer = socketIo(server, {transports: ['websocket']})
server.listen(8080)

Next, handle the socket events:

webSocketServer.on('connection', socket => {
  console.log(`A user connected with socket ${socket.id}`)

  socket.on('type1', dataFromClient => {
    logger.debug('got type1 frame from the client', dataFromClient)
  })
  
  socket.on('disconnect', () => {
    logger.debug('user socket disconnected')
  })
  
})

Summary

Javascript provides libraries that makes websocket implementation easy, and it take only few minutes to use it. Notice that to view the actual frame, you can use the chrome debugger network tab, see the Debugging WebSocket answer.

To view more details about the web socket library, check the socket-io home page.

No comments:

Post a Comment