ForgeTotal.js 5
en

Total.js 5

Connect to a WebSocket server from Node

Total.js 5 · total5@0.0.19 websocketrealtimeintegrations Executed against Total.js 5

WEBSOCKETCLIENT(function(client) {}) gives you a client. Call client.connect(url) with a ws:// or wss:// address, listen with client.on('open' | 'message' | 'close' | 'error', fn) and send with client.send(object); objects travel as JSON. Use client.headers and client.cookies to authenticate before connecting, and client.close() to disconnect.

The example connects to an echo socket of its own app; point it at any WebSocket server in real code.

controllers/echo.js
exports.install = function() {
	ROUTE('SOCKET /echo/', echo);
	ROUTE('GET /relay/', relay);
};

function echo() {
	this.on('message', function(client, message) {
		client.send({ echo: message.text });
	});
}

function relay($) {

	WEBSOCKETCLIENT(function(client) {

		client.connect($.hostname('/echo/').replace('http', 'ws'));

		client.on('open', function() {
			client.send({ text: 'ping' });
		});

		client.on('message', function(message) {
			client.close();
			$.json(message);
		});

		client.on('error', function(err) {
			$.invalid(err + '');
		});
	});
}