# Construir um chat WebSocket

> Declare uma rota SOCKET, escute mensagens e difunda-as a todos os clientes ligados.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: pt
Content-SHA256: 72a5385103b2a27c1771264cc844c5f75ea2501f4c83d31f6a80a513d6b92088
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

Um endpoint WebSocket declara-se com `ROUTE('SOCKET /path/', fn)`. Dentro do handler, `this` é o controlador WebSocket: use `self.on('message', ...)` para receber dados e `self.send(...)` para difundir a todos os clientes ligados. `client.send(...)` responde apenas a quem enviou. Os objetos são enviados e recebidos como JSON por omissão.

```js controllers/chat.js
exports.install = function() {
	ROUTE('SOCKET /chat/', socket);
};

function socket() {

	var self = this;

	self.on('message', function(client, message) {
		self.send({ type: 'message', text: message.text });
	});
}
```
