Newbie guide: socket.IO
Tags: javascript, node, express, newbie
Published: 2019-04-19 23:19:33

## 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
11. Conclusion
12. Resources

####[Note: This guide covers till setting up socket.IO to be used. A chat app using socket.IO will is in part 2](https://dev.to/kauresss/newbie-guide-socket-io-code-a-chat-app-part-2-2c47)

## 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:

 ![](https://thepracticaldev.s3.amazonaws.com/i/fuu3236jecf6n8y19gx3.png)

We now have:

![](https://thepracticaldev.s3.amazonaws.com/i/q3xun5q80dnv50km5xyt.png)

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?

![](https://thepracticaldev.s3.amazonaws.com/i/66e5g4wys44j3t6bkr14.png)

- 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


<b> 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

```
<b>Initialize npm<b>

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

```

<b>Install Express<b>

```
//install express
npm install express --save

```

<b>Install socket.IO<b>

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

```
<b>Install nodemon for convenience<b>

```
//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

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