Now let's create our chat application. Execute following commands to create a blank project and include all the required dependencies such as socket.io and express required for our project.
Now we will create a sample node app using express to serve a static .html file.Import the project in your favourite IDE and add a file name index.js add following lines in it.
Above code will initialise express and create a server that is listening on port 3000 and for a request at localhost:3000 Hello world will be served.
Now let us modify the code to serve a html.Create chat.html and add following lines to it.
This will create a simple form to enter message in the client side.
Now add following lines in index.js which will initialize a new instance of socket.io by passing the http object.
Whenever a client gets connected to a socket a connection event is raised and following code will listen to this event and logs the event for every new connection.
Now let us integrate socket in the client side. Add following lines in chat.html before the
tag. It will expose a global variable io and connect to the host that serves the page.Once a client gets connected in the browser, connect event is triggered and on a successful connection in the client side, client emits an event - joined which has a callback to send data to the server. And the server that is listening for the event - joined will receive the same data.chat.html
Now, once server finds that a new client has joined it will acknowledge the same to the client.index.js
This completes the initial binding between client and server.Now let us make provision for the chat between client and server.Whenever a client enters any message in the text box and hits enter, chat message event will be raised by the client and the server is listening to the same event. Whenever server finds any event with chat message, it will append 'from server ' in the message and emit 'response message' and the client will be listening to this event again and accordingly the chat window will be updated.chat.html
Above configuration will enable chat between a client and a server. We can also broadcast a same message to all the connected clients. For this purpose, we have broadcast flag.index.js
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.You can download the source code from github.
1. Rxjs Tutorial
2. Angular Material App
3. Typescript Tutorial
4. Nodejs Basic Tutorial
5. Install Nginx Php Mac
Suggest more topics in suggestion section or write your own article and share with your colleagues.
Contact us: email@example.com