In our previous blog Link, we learned how to configure the node with socket.io in Opencart. Today we will continue about how to use socket.io scripting programming in a chat application. We will learn how to send or receive messages through socket.io functions.
For the chat application, we have to manage two files:
1) Server File
2) Client File
In the previous blog, we create a package.json file for defining the dependencies that we required for our application, you have to create a server.js file parallel to package.json file to your Opencart root directory:
Opencart Company ? Read More
In server.js file we have to include all necessary dependencies at the top. We will also define the Global Configuration setting in server.js.
In the above screenshot, socket.emit () used to response back to the sender. You can also display on the terminal on connection or on disconnect with the server. See the below screenshot, you can console the message on disconnection. If you will refresh the page, then you will see the “You are disconnected!” on the terminal.
Now we will create the client.html file for the user to send the message. Firstly, we have to load a client library (socket.io.js) on browser for communication.
var socket = socket.io(http://[host]:[port]);
With the help of socket.io(http://) we can create an instance of socket.io by passing http object as an argument.
Now go to terminal and execute this below mentioned command to run the server.
$ node server.js
On server.js we will receive the user message and will console on terminal.
Thanks for reading this blog