Chat with nodejs or HTML (and socket.io)
Have you ever wanted to build a chat? Like @Vandesm14 Lowchat or repl talk? Well, this tutorial is for you. Today we are going to learn socket.io which you can use to create a chatting system.
Socket.io is a nodejs module (not only for nodejs) that allows real-time communication between the client and the server. It is way much faster than a get or post request. The way I am teaching you is the way I learned it so there are some easier ways to do this but this is how I learned it. To start we have to create two repls a nodejs repl and a html repl. On the nodejs repl enter the following code:
The first line is importing the module socket.io. As you can see we are also declaring the port in the first line when importing socket.io.
The connection listener is executed when a client or clients joins. Once you run that code you should see a server open up. Copy the link of the URL because we're gonna need it in our next step.
Connecting to the socket
To connect to our socket we need to add a script in our HTML with an src of the link of the socket with the URL of /socket.io/socket.io.js. So you need to add this to your HTML repl:
Doing that will automatically create a function in your script. Remember to import your script after importing the script I just showed you. In your script do this:
When we do that the connection listener on our server should fire up.
Sending and receiving data
Both the server and the client can receive and send data
While receiving data is the same process for server and client, sending data is not. To receive data from the server do this:
To recieve data from the client do this:
To send data in the server you use the io variable to emit your data to every client connected like this:
Sending data in the client is the same you just replace io with socket and it is socket.emit not socket.local.emit.
For more info go to this website
Upvote if you're a living thing
Upvote if you like.