Building Real-Time Applications with Vue.js and WebSockets

Emperor Brains
3 min readMay 24, 2024

--

Building Real-Time Applications with Vue.js and WebSockets

Introduction to Vue.js and WebSockets

Vue.js is a progressive JavaScript framework used for building user interfaces. Its reactive data binding and component-based architecture make it an excellent choice for dynamic applications.

WebSockets provide a full-duplex communication channel over a single TCP connection. Unlike HTTP, which is request-response-based, WebSockets allow for continuous two-way communication between the client and server, making them ideal for real-time applications.

Setting Up the Project

First, let’s set up a Vue.js project. If you haven’t already, install Vue CLI:

npm install -g @vue/cli

Create a new Vue.js project:

vue create real-time-app
cd real-time-app

Installing Socket.io

For our WebSocket implementation, we’ll use Socket.io. It simplifies the process of working with WebSockets and provides fallback options for older browsers.

Install Socket.io client:

npm install socket.io-client

Setting Up the Server

We’ll need a server to handle WebSocket connections. For this example, we’ll use Node.js with Express and Socket.io. Create a new directory for the server:

mkdir server
cd server
npm init -y
npm install express socket.io

Create a server.js file with the following content:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {
console.log('New client connected');

socket.on('message', (message) => {
console.log('Message received:', message);
io.emit('message', message); // Broadcast the message to all clients
});

socket.on('disconnect', () => {
console.log('Client disconnected');
});
});

server.listen(4000, () => {
console.log('Server is running on port 4000');
});

Connecting Vue.js to WebSockets

Now that we have our server set up, let’s connect our Vue.js application to it.

In your Vue.js project, create a new file src/socket.js and add the following code:

import io from 'socket.io-client';

const socket = io('http://localhost:4000');

export default socket;

Creating a Real-Time Component

Next, create a Vue component that will use the WebSocket connection to send and receive messages. Create a new file src/components/Chat.vue:

<template>
<div class="chat">
<div class="messages">
<div v-for="(message, index) in messages" :key="index" class="message">
{{ message }}
</div>
</div>
<input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message...">
</div>
</template>

<script>
import socket from '../socket';

export default {
data() {
return {
messages: [],
newMessage: ''
};
},
created() {
socket.on('message', (message) => {
this.messages.push(message);
});
},
methods: {
sendMessage() {
if (this.newMessage.trim() !== '') {
socket.emit('message', this.newMessage);
this.newMessage = '';
}
}
}
};
</script>

<style>
.chat {
display: flex;
flex-direction: column;
height: 100vh;
}
.messages {
flex: 1;
overflow-y: auto;
}
.message {
padding: 10px;
border-bottom: 1px solid #ccc;
}
input {
padding: 10px;
border: 1px solid #ccc;
width: 100%;
box-sizing: border-box;
}
</style>

Using the Chat Component

Finally, use the Chat.vue component in your main application. Update src/App.vue:

<template>
<div id="app">
<Chat />
</div>
</template>

<script>
import Chat from './components/Chat.vue';

export default {
components: {
Chat
}
};
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

Running the Application

To run the application, start both the server and the Vue.js app.

In the server directory:

node server.js

In the Vue.js project directory:

npm run serve

Open your browser and navigate to http://localhost:8080. You should see the chat interface. Open another browser tab or window to test real-time messaging between multiple clients.

Real-Time Application Development with Vue.js and WebSockets by Emperor Brains

Building real-time applications with Vue.js and WebSockets is a powerful approach to creating dynamic and interactive user experiences. By leveraging Vue.js’s reactive data binding and component-based architecture alongside the full-duplex communication capabilities of WebSockets, developers can achieve seamless real-time interactions between clients and servers.

In this guide, we walked through setting up a Vue.js project, integrating Socket.io for WebSocket communication, and creating a real-time chat application. This foundational knowledge can be extended to a variety of real-time applications such as collaborative tools, live updates, and interactive dashboards.

At Emperor Brains, we are dedicated to harnessing cutting-edge technologies to deliver robust and innovative web solutions. If you are looking to develop real-time applications or need expert assistance in web development, visit our website at Emperor Brains and explore how we can help turn your ideas into reality.

--

--