WebSockets enable real-time, bidirectional communication between the client and the server. Unlike traditional HTTP polling, WebSockets maintain an open connection, making them faster and more efficient for live updates like chat applications, stock prices, notifications, real-time dashboards, and multiplayer games.
1. Understanding WebSockets
WebSockets use the ws://
or wss://
protocol to establish a persistent connection.
ws://
→ Used for unsecured connectionswss://
→ Used for secure (SSL/TLS) connections
Use Cases:
- Chat applications
- Live notifications
- Real-time analytics dashboards
- Multiplayer gaming
- Collaborative editing
2. Setting Up a WebSocket Connection in AngularJS
Basic WebSocket Implementation
AngularJS does not have built-in WebSocket support, so we use JavaScript’s WebSocket API.
app.factory('WebSocketService', function($rootScope) {
var socket;
return {
connect: function(url) {
socket = new WebSocket(url);
socket.onopen = function() {
console.log('WebSocket Connected');
};
socket.onmessage = function(event) {
console.log('Received:', event.data);
$rootScope.$broadcast('websocketMessage', event.data);
};
socket.onclose = function() {
console.log('WebSocket Disconnected');
};
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
},
send: function(message) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(message);
} else {
console.error('WebSocket is not open.');
}
},
close: function() {
if (socket) {
socket.close();
}
}
};
});
Using WebSocketService in a Controller
app.controller('WebSocketController', function($scope, WebSocketService) {
WebSocketService.connect('ws://your-websocket-server');
$scope.$on('websocketMessage', function(event, data) {
console.log('Message received in Controller:', data);
$scope.receivedMessage = data;
$scope.$apply(); // Update UI
});
$scope.sendMessage = function() {
WebSocketService.send($scope.messageText);
$scope.messageText = ''; // Clear input
};
});
HTML UI for WebSockets
<div ng-controller="WebSocketController">
<h3>WebSocket Chat</h3>
<input type="text" ng-model="messageText" placeholder="Type a message">
<button ng-click="sendMessage()">Send</button>
<p>Received Message: {{ receivedMessage }}</p>
</div>
How It Works?
- The service connects to the WebSocket server.
- It listens for messages and broadcasts them.
- The controller updates the UI with new messages.
- Users can send messages to the WebSocket server.
3. Using $timeout
to Avoid $digest
Issues
When data updates occur outside AngularJS’ digest cycle, use $timeout
to trigger updates.
app.controller('WebSocketController', function($scope, WebSocketService, $timeout) {
$scope.messages = [];
$scope.$on('websocketMessage', function(event, data) {
$timeout(function() {
$scope.messages.push(data);
});
});
});
4. Handling WebSocket Reconnection
To handle WebSocket disconnects and reconnections, modify WebSocketService
:
app.factory('WebSocketService', function($rootScope, $timeout) {
var socket, reconnectTimeout;
function connect(url) {
socket = new WebSocket(url);
socket.onopen = function() {
console.log('WebSocket Connected');
};
socket.onmessage = function(event) {
$rootScope.$broadcast('websocketMessage', event.data);
};
socket.onclose = function() {
console.log('WebSocket Disconnected, reconnecting in 3 seconds...');
reconnectTimeout = $timeout(function() {
connect(url);
}, 3000);
};
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
}
return {
connect: connect,
send: function(message) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(message);
}
},
close: function() {
if (socket) {
$timeout.cancel(reconnectTimeout);
socket.close();
}
}
};
});
Features:
- Automatically reconnects after disconnection.
- Uses
$timeout
to retry after 3 seconds. - Stops reconnecting when the app is closed.
5. Using WebSockets with RxJS for Better Management
RxJS makes it easier to handle WebSocket connections reactively.
Install RxJS
npm install rxjs --save
WebSocket Service with RxJS
app.factory('WebSocketService', function($rootScope) {
var subject;
function connect(url) {
subject = new Rx.Subject();
var socket = new WebSocket(url);
socket.onmessage = function(event) {
subject.next(event.data);
};
socket.onclose = function() {
console.log('WebSocket Disconnected');
};
return subject;
}
return {
connect: connect
};
});
Consuming WebSocket in a Controller
app.controller('WebSocketController', function($scope, WebSocketService) {
var socketStream = WebSocketService.connect('ws://your-websocket-server');
socketStream.subscribe(function(message) {
$scope.$apply(function() {
$scope.receivedMessage = message;
});
});
});
Why Use RxJS?
✔ Handles real-time data streams efficiently
✔ Supports automatic reconnects
✔ Works great for multiple subscribers