Using socket.io for real-time applications

Loading

Socket.IO is a JavaScript library that enables real-time, bidirectional, event-based communication between web clients and servers. It is commonly used for chat applications, live notifications, real-time analytics, stock price updates, and collaborative tools.


1. Setting Up Socket.IO in an AngularJS Application

To use Socket.IO with AngularJS, we need to set up both the server-side and client-side.

Step 1: Install Socket.IO

If you’re using Node.js as your backend, install Socket.IO using npm:

npm install socket.io

If using Express, install both:

npm install express socket.io

2. Setting Up the Server-Side (Node.js + Express)

The backend listens for Socket.IO events and sends updates to connected clients.

Step 2: Create an Express Server with Socket.IO

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, {
cors: {
origin: "*", // Allow all origins (modify for security)
methods: ["GET", "POST"]
}
});

io.on("connection", (socket) => {
console.log("A user connected: " + socket.id);

// Listen for messages from clients
socket.on("chatMessage", (message) => {
console.log("Received message: " + message);

// Broadcast the message to all connected clients
io.emit("chatMessage", message);
});

socket.on("disconnect", () => {
console.log("User disconnected: " + socket.id);
});
});

// Start server
server.listen(3000, () => {
console.log("Server running on port 3000");
});

3. Integrating Socket.IO with AngularJS (Client-Side)

The AngularJS application needs to connect to the Socket.IO server and send/receive events.

Step 3: Include Socket.IO in Your AngularJS App

Add this in your index.html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>

4. Creating an AngularJS Service for Socket.IO

To keep Socket.IO integration modular and reusable, use an AngularJS service.

Step 4: Create a Socket Service

var app = angular.module("socketApp", []);

app.factory("SocketService", function($rootScope) {
var socket = io.connect("http://localhost:3000"); // Connect to the server

return {
on: function(eventName, callback) {
socket.on(eventName, function(data) {
$rootScope.$apply(function() {
callback(data);
});
});
},
emit: function(eventName, data) {
socket.emit(eventName, data);
}
};
});

5. Creating a Chat Controller in AngularJS

Now, let’s create a chat application where users send and receive messages in real-time.

Step 5: Implement the Chat Controller

app.controller("ChatController", function($scope, SocketService) {
$scope.messages = [];
$scope.newMessage = "";

// Receive messages from server
SocketService.on("chatMessage", function(message) {
$scope.messages.push(message);
});

// Send message to server
$scope.sendMessage = function() {
if ($scope.newMessage.trim() !== "") {
SocketService.emit("chatMessage", $scope.newMessage);
$scope.newMessage = ""; // Clear input after sending
}
};
});

6. Creating a Simple Chat UI

Modify index.html to include:

<div ng-app="socketApp" ng-controller="ChatController">
<h3>Real-Time Chat</h3>
<div id="chat-box">
<div ng-repeat="message in messages track by $index">
{{ message }}
</div>
</div>
<input type="text" ng-model="newMessage" placeholder="Type a message..." />
<button ng-click="sendMessage()">Send</button>
</div>

7. Broadcasting Real-Time Updates

In addition to chat, you can use Socket.IO for:

  • Live Notifications
  • Stock Price Updates
  • Real-Time Analytics
  • Collaborative Editing

Modify the server to send real-time notifications:

io.on("connection", (socket) => {
console.log("A user connected: " + socket.id);

// Send a welcome message when a user connects
socket.emit("notification", "Welcome to the chat!");

socket.on("disconnect", () => {
console.log("User disconnected: " + socket.id);
});
});

8. Handling Disconnections and Reconnects

Handle disconnect events in the AngularJS service:

socket.on("disconnect", function() {
console.log("Disconnected from server.");
});

socket.on("connect", function() {
console.log("Reconnected to server.");
});

Leave a Reply

Your email address will not be published. Required fields are marked *