We can get WebSockets working with the Application Load Balancer, for that:
First, create a new Target Group for your ALB, This target Group should use the same port as your application and will need to have health checks configured.
Then, add a new Listener Rule to your ALB and this rule must have a Path to route the WebSocket setup -- /socket.io. Also, set the Target Group Name to the Target Group that you created just now.
I'm using Node/Hapi/Socket.io for my server, basic setup is:
const hapi = require('hapi');
const websocket = require('./WebSocket');
var server = new hapi.Server();
server.connection(config.Application);
websocket.Initialize(server.listener);
where WebSocket.js is:
var io = null;
module.exports = {
Initialize: function (http) {
io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('Websocket ' + socket.id + ' connected.');
socket.on('disconnect', function () {
console.log('Websocket ' + socket.id + ' disconnected.');
});
});
}
};
I'm using Angular 1.5x for my client, with the socket.io-client. It is important to configure the WebSocket client option as follows, or you will not be able to connect.
(function () {
'use strict';
angular
.module('XXXXX', [])
.run(runHandler);
runHandler.$inject = ['WebSocketService'];
function runHandler(WebSocketService) {
WebSocketService.Initialize();
}
})();
The WebSocket service:
(function () {
'use strict';
angular
.module('XXXXX')
.factory('WebSocketService', WebSocketService);
WebSocketService.$inject = [];
function WebSocketService() {
var socket = null;
function initialize() {
var url = 'http://' + ALB_URL + ':5800';
socket = io(url, {transports: ['websocket'], upgrade: false});
socket.on('connect', function () {
console.log('Socket connected');
});
socket.on('disconnect', function () {
console.log('Socket disconnected');
});
}
return {
Initialize: initialize
};
}
})();
Want to become AWS Expert? Come & join AWS Certification.