/ node

Use Socket.io for Real Time Client/Server Communication

In this article, we're going to look at using Socket.io with our Node and Express applications. To consume the events, we'll be using Angular, but you're welcome to use any client you want.

Getting Started

Let's start by making a new project where our server will reside. I'll create a new project and install express and socket.io. We'll then initialise our server to listen for connections and emit events.

# Create a new folder
$ mkdir socket-greeting

# Change directory
$ cd socket-greeting

# Install dependencies
$ npm install socket.io express

# Create server.js file
$ touch server.js

# Open in editor
$ code .

Server

Inside of our server.js, we'll import all of our dependencies and create a new HttpServer at port 3000. We're then using res.send to send the text 'Hello World' at the root localhost:3000 to check everything works as intended.

const express = require('express'), 
      http = require('http'),
      socketIo = require('socket.io'),
      app = express(),
      server = http.Server(app);

app.get('/', (req, res) => res.send("Hello World"));

server.listen(3000);

Using Socket.io

Now that we can access our server via URL, we can watch for client connections, and emit an event when a client accesses our server. I've elected to emit a simplistic event named hello with the payload of {greeting: 'Hello Paul'}.

const io = socketIo(server);

io.on('connection', (socket) => {
    socket.emit('hello', {
        greeting: 'Hello Paul'
    });
});

That's all we need at the moment for our server, so let's run it with node server.

Client

To access the hello event inside of our client application, let's create a new Angular project and install socket.io. We can do this by using npm and the Angular CLI:

# Install the Angular CLI
$ npm install @angular/cli -g

# Create a new Angular project
$ ng new NgSockets

# Change directory
$ cd NgSockets

# Install socket.io
$ npm install socket.io

# Run project
$ ng serve

# Open in editor
$ code .

Using Socket.io within Angular

Our Angular application has the job of listening for an event at http://localhost:3000 (our Node instance) and then performing an action based on that event. We can do all of this inside of our app.component.ts.

I'll be using the lifecycle event OnInit and logging the emitted event out to the console.

import { Component, OnInit } from '@angular/core';
import * as socketIo from 'socket.io-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit(): void {
    const socket = socketIo('http://localhost:3000');

    socket.on('hello', (data) => console.log(data));
  }
}

The above code allows us to listen for the hello event and subsequently log the value using socket.on('hello'). If we were to emit another event from the server, our client would be updated providing the event itself is still named hello.

socket-emit-log

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More