Why do we need http for socket.io?
So, a socket is basically an upgraded version of the normal HTTP (TCP) connection. Now, it needs to hook to the low level HTTP server to upgrade this one-time tcp connection into a websocket connection. Now, while the normal app.listen() is a wrapper over the HTTP connection, it does not provide the connection with HTTP that the socket.io needs.
So we should create a basic server first.
So we need to create a HTTP server first, then hook that server to the socket.io.
import {createServer} from 'http'; import {Server} from 'socket.io'; const httpserver = createServer(app); const io = new Server(httpserver);
Now, we have a new socket. Now we need to listen to the incoming connection.
io.on('connection', (socket) => { console.log("user is connected.") })
Now, while we have created a socket.io server, we also need to make sure that a client who opens the website on browser is being able to connect with this server. So, to do that we add the following lines in our .html files.
<script src="/socket.io/socket.io.js"></script> <script>let socket = io();</script>
So, when we create a socket.io server, it automatically attaches a special route ‘/socket.io/socket.io.js’ that serves the client library. Now the first line, allows our client to connect to the server and receive or send message through this connection. The second line initiates a websocket connection from the browser to the Socket.IO server.