Websocket Socket.io HelloWorld | Cameron Sim

Today we will build a hello world example webscoket application to send messages from the client (browser) to the server This will only take about 10 minutes for this guide and will show basic use of sending messages & events via websocket.

Getting Started

  1. Install Nodejs if you haven't already you can download from here Download NODEJS

  2. Create a new dir in your workstation directory or where you will be serving your nodejs application from: For example I have created the following mkdir ~/Documents/Websocket-HelloWorld

  3. Enter into the directory and install websocket package, There is loads of websocket packages available, but we will ben installing socket.io the by running the following commands npm install express && npm install socket.io do this in your new websocket directory cd ~/Documents/Websocket-HelloWorld

Here is a list of the commands

foo@bar:~$ mkdir ($WORKSTATIONLCOATION)
foo@bar:~$ cd ($WORKSTATIONLCOATION)
foo@bar:~$ npm install express
foo@bar:~$ npm install socket.io

Lets setup our application now:

Create a new file called index.js In this is where we are going to be writing our socket listeners and start our socket.io.

In index.js you have just created add the following to the top.

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

this is including all our modules needed for the websockets and defining the required variables.

Next lets start it up add the following also to the index.js

server.listen(3000, () => {
    console.log('listening on *:3000');
});

Good, we will be listening on port 3000, but what are we listening for? yeah lets add something to catch on that port add the following to the same index.js

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
});

Good we can now catch messages on port 3000 via 'Chat Message' lets add a default router for our application to server our basic webpage. add the following to index.js

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/message.html');
});

The full index.js file should look like the following

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/message.html');
});

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
});

server.listen(3000, () => {
    console.log('listening on *:3000');
});

Brilliant. now we need the client side so let's create a new file called message.html

Lets create our html basic structure.

<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO HelloWorld</title>
</head>
<body>
</body>
</html>

Next we will need to add some content, lets add an area for messages and some styling

between the <head> tags add the following style tags

<style>
    body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

    #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
    #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
    #input:focus { outline: none; }
    #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

    #messages { list-style-type: none; margin: 0; padding: 0; }
    #messages > li { padding: 0.5rem 1rem; }
    #messages > li:nth-child(odd) { background: #efefef; }
</style>

Great, lets add some content now, add the following between <body> tags

<ul id="messages"></ul>
<form id="form" action="">
    <input id="input" autocomplete="off" /><button>Send</button>
</form>

Good so we now have a basic static html site. It wont do anything just yet, we already have our socket running on port 3000 so we need to make sure we are catching its messaging and that we can send some to it.

lets get started by including and initializing socket io on our static site, you can do this by including the following before the closing </body> tag

<script src="/socket.io/socket.io.js"></script>

Okay lets now add some logic to send and get messages from socket.io add the following underneath the the socket.io script

<script>
    var socket = io();

    var messages = document.getElementById('messages');
    var form = document.getElementById('form');
    var input = document.getElementById('input');

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
            socket.emit('chat message', input.value);
            input.value = '';
        }
    });

    socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
    });
</script>

Lets break this down.

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
            socket.emit('chat message', input.value);
            input.value = '';
        }
    });

above we are capturing the text on our form input and using the socket libary to emit a message called (chat message) with the value of our form input

    socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
    });

Here we are listening for a message being received on the socket, if a new message is received we are inserting it into our static site the value as a list item to create a message list effect.

Here is the message.html complete

<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

        #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
        #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
        #input:focus { outline: none; }
        #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages > li { padding: 0.5rem 1rem; }
        #messages > li:nth-child(odd) { background: #efefef; }
    </style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
    <input id="input" autocomplete="off" /><button>Send</button>
</form>

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();

    var messages = document.getElementById('messages');
    var form = document.getElementById('form');
    var input = document.getElementById('input');

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
            socket.emit('chat message', input.value);
            input.value = '';
        }
    });

    socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
    });
</script>
</body>
</html>

Thats us to start our application we will run our website by using the following command node index.js

foo@bar:~$ node index.js

Once running we should piont our browser to http://localhost:3000 to see our application and test it out

Amazing, that's the first socket.io application done. we can expand this evan further and send files or store and retrieve data from a database

Checkout this example here on github Websocket HelloWorld Example Good Luck!