What is Websocket ?
Tags: webdev, websocket, programming
Published: 2023-03-07 08:43:40

 
WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is used for real-time web applications such as chat applications, gaming applications, and other applications where real-time data transfer is required. WebSocket enables two-way communication between a client and a server, which allows data to be sent from both the client and the server at any time.

WebSocket is supported by almost all modern web browsers and is widely used in web development. It has many advantages over traditional HTTP requests, such as faster communication, low latency, and reduced server load.
Websocket protocol is similar to HTTP but unlike HTTP, WebSocket keeps the connection open and allows data to be transferred in both directions at any time.

In WebSocket, the server and client exchange data in frames. The data frames are sent over a single TCP connection, which is kept open for the duration of the communication. The frames can be sent in either direction, which allows for two-way communication.
Creating a Chatroom with Socket.io
Socket.io is a JavaScript library that enables real-time, bidirectional, and event-driven communication between the web browser and the server. It provides an easy-to-use interface for creating real-time web applications such as chat applications, gaming applications, and other applications that require real-time data transfer.

In this example, we will create a chatroom application with a backend using Node.js, Express, and MongoDB, and a frontend using Vue.js.

## Backend

We will start by creating the backend of the application using Node.js, Express, and MongoDB.
Setting up the environment
Before we start, we need to set up the environment. We need to install Node.js, MongoDB, and Express.
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It is used for building scalable network applications. MongoDB is a NoSQL database that provides high performance, high availability, and automatic scaling. Express is a minimalist web framework for Node.js.

## 
Creating the server

We will create the server using Express. Here is the code:
`const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
http.listen(3000, () => {
    console.log('listening on *:3000');
});
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});`

In the above code, we created an Express application, created an HTTP server using the createServer() method, and created a Socket.io instance using the server. We then started the server listening on port 3000 and served the index.html file for the root route.

## Setting up the database

We will use MongoDB as our database. Here is the code for connecting to the database:
`const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/chatroom', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB');
});`

In the above code, we used the Mongoose library to connect to the MongoDB database. We then created a database connection and listened for any errors or successful connections.

## Creating the chatroom

We will create the chatroom using Socket.io. Here is the code:
`io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
    socket.on('chat message', (msg) => {
        console.log('message: ' + msg);
        io.emit('chat message', msg);
    });
});`

In the above code, we created a Socket.io connection listener that listens for incoming connections. When a connection is established, we log a message to the console. When the connection is closed, we log another message to the console. We also listen for a chat message event and broadcast the message to all connected clients.

## Frontend

We will now create the frontend of the application using Vue.js.
Setting up the environment
Before we start, we need to set up the environment. We need to install Vue.js and Socket.io-client.
Vue.js is a JavaScript framework for building user interfaces. It is designed to be simple and flexible. Socket.io-client is a client-side library for Socket.io.

## Creating the chatroom

We will create the chatroom using Vue.js and Socket.io-client. Here is the code:
`<template>
    <div>
        <ul id="messages">
            <li v-for="message in messages">{{ message }}</li>
        </ul>
        <form @submit.prevent="sendMessage">
            <input v-model="message" autocomplete="off" /><button>Send</button>
        </form>
    </div>
</template>
<script>
import io from 'socket.io-client';
export default {
    data() {
        return {
            message: '',
            messages: []
        }
    },
    created() {
        this.socket = io('<http://localhost:3000>');
        this.socket.on('chat message', (msg) => {
            this.messages.push(msg);
        });
    },
    methods: {
        sendMessage() {
            this.socket.emit('chat message', this.message);
            this.message = '';
        }
    }
}
</script>`

In the above code, we created a Vue.js component that displays a list of messages and a form for sending new messages. We also created a Socket.io connection to the server and listened for incoming chat message events. When a message is received, we add it to the list of messages. When a new message is sent, we emit a chat message event to the server.

## Conclusion

In this example, we have created a chatroom application using Socket.io, Node.js, Express, MongoDB, and Vue.js. Socket.io provides an easy-to-use interface for creating real-time web applications, and Node.js, Express, and MongoDB provide a robust backend for our application. Vue.js provides a simple and elegant frontend for our application. We hope this example has been helpful in understanding how to create real-time web applications using Socket.io.