# Connect to a WebSocket server from Node

> Use WEBSOCKETCLIENT to open a WebSocket connection from your app, send messages and react to the answers.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 4f9fb10635b7e3d5c35888a6df54fadfa832a9d2bdc4701c8b2c7c68b702e1b3
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`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.

```js 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 + '');
		});
	});
}
```
