If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To begin the initial connection with Socket.io, we first need to set up the server-side code. We will create a new file index.js
inside the sockets
folder and set up the basic Socket.io connection.
First, we need to install the socket.io
package using NPM:
luaCopy code
npm install socket.io
Then, in our index.js
file, we can set up the basic server-side code as follows:
javascriptCopy code
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('A user connected!');
});
Here, we are initializing a new instance of Socket.io and passing in our server instance as an argument. We then attach a listener to the connection
event, which fires whenever a client connects to our server. In this case, we simply log a message to the console to confirm that a user has connected.
We can now run the server and test the connection by opening a client-side Socket.io connection. In our index.ejs
file, we can add the following script tag to establish a client-side connection:
htmlCopy code
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('connect', () => {
console.log('Connected to server!');
});
</script>
Here, we are including the Socket.io client-side script, then initializing a new instance of Socket.io and attaching a listener to the connect
event. When this event fires, we log a message to the console to confirm that we have successfully connected to the server.
Now, when we run our application and open it in the browser, we should see two messages in the console: "A user connected!" (from the server-side code) and "Connected to server!" (from the client-side code), confirming that our Socket.io connection is working properly.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.