DEV Community

BillyGoat12
BillyGoat12

Posted on • Updated on

Intro into WebSocket

Axios Request

We would need to know a bit about axios requests before we can understand websockets. Axios requests are awesome because they allow users to make requests from the browser to the client and send a response back per request. This is normally great because if you want more information you just ask the server for it without having to refresh the page but what would happen if you want to do something a bit more real time? If we tried to make our application to work in real time with axios then we would have to either set up a button that loads current feeds or have the client browser send an infinite amount of requests to the server. There are several flaws with this approach, the button approach is not very user friendly and the infinite request will cause too many issues. This is where websockets come into play.

What Are Websockets

Websocket is kinda like axios but better. What a websocket does is that when a client sends a request to the server, the server listens on the request and sends back a response to all the clients that are connected to that server. This is why websocket is considered ideal implementation when it comes to working with real time.

Implementation

There are many different apis we can use to implement websocket but today we will only be talking about Socket.IO implementations. If you want to go to the docs for this api here is the link: https://socket.io/docs/v3/index.html. Without further ado, we can start talking about implementations. First we will have to install socket.io and http then import those on your server page. Then you will need to add const server = http.createServer(app); and
const io = socketio(server); to your server page. After that you will have to change your app.listen to server.listen. Now somewhere in the middle of your page you can add
io.on('connection', (socket) => {
socket.on('sent', () => {
io.emit('received');
});
});
what this does is io.on connection happens when a user connects to the server and then when a user browser emits a sent the server gets it and emits a 'received' to all the client browser. Here is what your server page should look like.

const express = require('express');
const path = require('path');
const http = require('http')
const socketio = require('socket.io')


const app = express();
app.use(express.json());
const server = http.createServer(app);
const io = socketio(sever)

const DIST_DIR = path.join(__dirname, '../client', 'dist');
app.use(express.static(DIST_DIR))

io.on(‘connection’, (socket) => {
  socket.on(‘sent’, () => {
    io.emit(‘received’);
  })
});

server.listen(5000, function() {
    console.log('listen on: http://localhost:5000')
});
Enter fullscreen mode Exit fullscreen mode

Then on your front end you will add const socket = io(); and then set up a button that when clicked it will emit sent. socket.emit('sent');

socket.on('received', () => {
console.log(‘hello’)
});

What this does is when your server emits ‘received’ then it will invoke this function.
Here is what your code should look like.

Const socket = io();
Const app = () => {
  socket.on(‘received’, () => {
    console.log(‘hello’);
  });

  Return (
  <div>
  <button onClick={() => socket.emit(‘sent’)}>click</button>
  </div>
  )

}
Enter fullscreen mode Exit fullscreen mode

Lastly you will need to add a script tag to you index.html and is should be like this ** ** and your file should look like this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>live</title>
</head>
<body>
    <div id="root"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="bundle.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

conclusion

So now when you start your server and open two tabs and then on one tab click the button and the other tab should log to the console hello and this should work vice versa. Ultimately you will use this pattern to implement live data.

Top comments (0)