WebSocket Basics : Streaming Data from Server

In the previous article, we saw how to send data from the client to the server. In this article, we will see how to send data from the server to the client. Create index.html that will display the random number generated by the server to the browser.

<!DOCTYPE html>
<html lang="en">
<title>Random Number Generator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    var ws = new WebSocket("ws://localhost:8080");
    ws.onopen = function(e) {
      console.log('Connected to server');
      ws.onmessage = function(event) {
        $( '#randomNums' ).append(event.data + ' ');
<body lang="en">

  <div id="randomNums"></div>    


We first establish connection to the server. We are now ready to receive messages from the server in the onmessage handler. When we receive a data from the server, we append the number to the div with id randomNums. Whenever the data is received from the server, the onmessage javascript function is fired.

Create server.js that creates a WebSocketServer listening on port 8080. It sends a random number once every second. The setInterval function is used to stream random number at one second at a time to the client so that we can see the numbers emerging one by one in the browser. In a real app like tennis score board, there will be an unknown amount of delay in getting the latest score. The score board on the browser will be updated whenever the point is won. I used the Server example found in the ws library github home page as a starting point for this demo.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);

  var clientRandomNumberUpdater;
  var sendRandomNumbers = function(ws) {
    var randomNum = Math.floor(Math.random() * 11);  
  clientRandomNumberUpdater = setInterval(function(){
  }, 1000);  

Modify this demo so that the client sends a string when it connects and the existing code for the server already prints it to the console. You can verify the message sent by the client is received by the server by looking at the code. You can read the previous article on how to complete this exercise. You can download the source for this article from my github repo websocket.

Related Articles

Watch this Article as Screencast

You can watch this as a screencast WebSocket Basics : Streaming Data from Server

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.