WebSockets provide a real-time, full-duplex communication channel between the client and server, making them ideal for live updates, notifications, chat applications, stock market data, etc. In AngularJS, WebSockets can be implemented using the $websocket
service from the angular-websocket
library.
1. Why Use $websocket
in AngularJS?
✔ Real-time Data Updates – Keeps the client updated instantly.
✔ Efficient Communication – Reduces overhead compared to HTTP polling.
✔ Full-Duplex Connection – Server and client can send messages simultaneously.
✔ Better Performance – Uses fewer resources compared to HTTP requests.
2. Setting Up $websocket
in AngularJS
Step 1: Install angular-websocket
Library
Using npm:
npm install angular-websocket --save
Using bower:
bower install angular-websocket --save
Include it in HTML (if using CDN):
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-websocket/2.0.1/angular-websocket.min.js"></script>
Step 2: Add Dependency in AngularJS Module
var app = angular.module('myApp', ['ngWebSocket']);
3. Creating a WebSocket Service with $websocket
Let’s create an AngularJS service to manage WebSocket connections.
app.factory('WebSocketService', function($websocket) {
// Define WebSocket connection URL
var wsUrl = "wss://example.com/socket";
// Create WebSocket connection
var dataStream = $websocket(wsUrl);
var messages = [];
// Handle incoming messages
dataStream.onMessage(function(message) {
console.log("Received: ", message.data);
messages.push(JSON.parse(message.data)); // Store messages in an array
});
return {
messages: messages,
send: function(data) {
dataStream.send(JSON.stringify(data)); // Send data to server
},
close: function() {
dataStream.close(); // Close WebSocket connection
}
};
});
Explanation:
- Establishes a WebSocket connection with
wss://example.com/socket
. - Listens for incoming messages and stores them in an array.
- Provides methods to send messages and close the connection.
4. Using WebSocket in AngularJS Controller
app.controller('WebSocketController', function($scope, WebSocketService) {
$scope.messages = WebSocketService.messages;
// Send a message
$scope.sendMessage = function() {
WebSocketService.send({ text: "Hello WebSocket!" });
};
// Close connection
$scope.closeConnection = function() {
WebSocketService.close();
};
});
What Happens?
- Binds incoming WebSocket messages to
$scope.messages
. - Sends a message when
sendMessage()
is triggered. - Closes the WebSocket connection when
closeConnection()
is called.
5. Full HTML + AngularJS WebSocket Example
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>AngularJS WebSocket Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-websocket/2.0.1/angular-websocket.min.js"></script>
<script>
var app = angular.module('myApp', ['ngWebSocket']);
app.factory('WebSocketService', function($websocket) {
var wsUrl = "wss://example.com/socket";
var dataStream = $websocket(wsUrl);
var messages = [];
dataStream.onMessage(function(message) {
messages.push(JSON.parse(message.data));
});
return {
messages: messages,
send: function(data) {
dataStream.send(JSON.stringify(data));
},
close: function() {
dataStream.close();
}
};
});
app.controller('WebSocketController', function($scope, WebSocketService) {
$scope.messages = WebSocketService.messages;
$scope.sendMessage = function() {
WebSocketService.send({ text: "Hello WebSocket!" });
};
$scope.closeConnection = function() {
WebSocketService.close();
};
});
</script>
</head>
<body ng-controller="WebSocketController">
<h2>AngularJS WebSocket Example</h2>
<button ng-click="sendMessage()">Send Message</button>
<button ng-click="closeConnection()">Close Connection</button>
<h3>Messages:</h3>
<ul>
<li ng-repeat="message in messages">{{ message.text }}</li>
</ul>
</body>
</html>
6. Advanced Features with $websocket
Handling Connection Errors
You can detect WebSocket errors using .onError()
dataStream.onError(function(event) {
console.error("WebSocket Error: ", event);
});
Auto-Reconnect WebSocket Connection
var dataStream = $websocket(wsUrl, null, { reconnectIfNotNormalClose: true });
This ensures WebSocket reconnects automatically if the connection is lost.
Listening for WebSocket Close Events
dataStream.onClose(function(event) {
console.warn("WebSocket Closed: ", event);
});
This can help trigger alerts or reinitialize WebSockets when needed.
7. Comparing $websocket
with Raw JavaScript WebSockets
Feature | $websocket | Native WebSockets |
---|---|---|
Ease of Use | Simple, with built-in methods | Manual implementation required |
Auto-Reconnect | Built-in | Needs extra logic |
Message Handling | .onMessage() | socket.onmessage |
AngularJS Integration | Works with $scope | Requires $apply() to update scope |