DEV Community

loading...

Newbie guide: socket.IO

kauresss profile image Kauress ・4 min read

Guide

  1. Introduction
  2. What happens?
  3. Summary
  4. Set up the main project directory
  5. Install dependencies
  6. Directory structure
  7. Create a server in index.js
  8. Set up index.html
  9. Test your server 10.Make your first socket connection
  10. Conclusion
  11. Resources

Note: This guide covers till setting up socket.IO to be used. A chat app using socket.IO will is in part 2

Introduction

Socket.IO is a JavaScript library which allows real time bidirectional communication. Which means fast! and without reloading the page. Socket.IO is based of the websockets API,that allows for a tunnel of direct communication between the server and client to remain open.

Diagramtically instead of this:

We now have:

So the server can't send messages on it's own to the client. The browser must be refreshed and the message is requested from the server. However sockets.io allows for instantaneous communication.

When we request a URL from the browser we open a chat socket connection with the server.

What happens?

  • Data flows back and forth between the client and server
  • A client 'A' sends a message to the server
  • The chat server receives the message
  • The server decides to send the message to all connected clients so that they can see the message sent by client 'A'

Summary

Take away:

  • Sockets.io is a JS library
  • Enables biltaeral communication
  • Real time synchronous communication between client side and server
  • Built upon other real time protocol such as the websockets API
  • Event driven
  • Has 2 parts: 1. Client side library in the browser 2. Server side library for Node

So when using socket.IO you are playing ball with 2 files at the same time example chat.js (client side) and index.js (server side).
This is because you must write the code/logic to send a message from either the server/client and then receive it at the other side which is the client/server.

Set up the main project directory

//make a new folder
mkdir chat_app

//navigate to the folder
cd chat_app

Install dependencies

In your terminal install dependencies using npm. First check if you have node and npm installed with:

node -v
npm -v

Initialize npm

//create the package JSON file which will list all the dependencies used in the project
//leave index.js as the entry point
npm init

Install Express

//install express
npm install express --save

Install socket.IO

//install socket.io
npm install socket.io --save

Install nodemon for convenience

//automatically restarts server upon detecting changes
npm install nodemon --save-dev

Directory structure

Inside the main chat_app folder (not inside node_modules folder):

  1. Create a public folder and include:
    • index.html
    • style.css
    • chat.js

[path for navigation: /index.html, /style.css, /chat.js]

Your directory structure will look like this:

chat_app
├── node_modules
├── public
│ └── index.html
│ └── style.css
│ └── chat.js
├── index.js
├── package.json

Create a server in index.js

In index.js create a node.js server using express

// require express first
var express = require("express");
//require socket.IO
var socket = require('socket.io')

//setting up the express app by invoking the express function
var app = express();

//now create a server
//When the server starts listening on port 4000 then fire a callbak function
// The callback function will console.log a string 
var server = app.listen(4000, function(){
 console.log("Listening to requests on port 4000");

});
// serve a static file to the browser 
app.use(express.static("public"));

//Socket setup
//passing var server to the socket function and assigning it to var io
//essentially now socket.IO will work on this server just created
var io = socket(server);

Set up index.html

In index.html:

  • include the reference to the socket.io library
  • include the reference to the JavaScript file which contains client side socket.io code
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Newbie Guide</title>
       <script src="/socket.io/socket.io.js"></script>
        <link href="/style.css" rel="stylesheet" />
    </head>
    <body>
        <h1>Socket.io</h1>
    <script src="/chat.js"></script>
    </body>
</html>

Test your server

In the terminal, restart your server with:

//if using nodemon
nodemon 

//if using node
node index.js

You should see something console.logged in your terminal

[nodemon] 1.18.11
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
listening for requests on port 4000,

In the browser go to http://localhost:4000/
You should see your webpage up there. Now you're ready to actually start using socket.IO!

Make your first socket connection

In index.js

//declare var io which is a reference to a socket connection made on the server
var io= socket(server);

//Then use the io.on method which looks for a connection
//upon a connection execute a callback function which will console.log something
io.on('connection', function(){
  console.log('made socket connection');
});

In chat.js

//you already included a reference to the socket.io library in index.html so now you have access to it
//make a socket by declaring var socket which will make a socket connection to localhost:4000
var socket = io.connect("http://localhost:4000");

In the terminal:

nodemon

And then check for the console.log message in the terminal:

[nodemon] 1.18.11
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
listening for requests on port 4000,
made socket connection

Conclusion

And now you're ready to start using socket.IO on both the server and client to make something fun like a chat app. More in part 2..

Resources

  1. https://socket.io/
  2. https://openclassrooms.com/en/courses/2504541-ultra-fast-applications-using-node-js/2505653-socket-io-let-s-go-to-real-time
  3. https://sabe.io/tutorials/how-to-build-real-time-chat-app-node-express-socket-io
  4. https://socket.io/docs/client-api/#socket-on-eventName-callback
  5. http://wern-ancheta.com/blog/2013/08/25/creating-a-real-time-chat-application-with-socket-dot-io/
  6. http://danielnill.com/nodejs-tutorial-with-socketio

Discussion (6)

pic
Editor guide
Collapse
akaustav profile image
Ameet Kaustav

I apologize in advance for pointing out a typo in your code under the section titled - Create a server in index.js:

/setting up the express app by invoking the express function

should probably be:

//setting up the express app by invoking the express function
Collapse
kauresss profile image
Kauress Author

Thanks Ameet for pointing that out! Changed

Collapse
uddeshjain profile image
Uddesh

Great explanation. Waiting for next part.

Collapse
kauresss profile image
Collapse
thewashiba profile image
Lukas

Why are you using var?

Collapse
kauresss profile image
Kauress Author

As this is a newbie article on socket.IO, I wanted to make it accessible to all and focus on socket.IO, instead of explaining variable scope and hoisting so used the more familiar 'var'. In the socket.IO project I will use let and const