Socket.IO é uma biblioteca que possibilita comunicação em tempo real e bidirecional baseada em eventos entre o browser e o server.
Isso consiste em:
- Um servidor Node.js
- Uma biblioteca Javascript para o browser (Que também pode ser executada do Node.js)
npm install [email protected] express
npm install -D @types/socket.io @types/express typescript
Gerar o arquivo de configuração do typescript:
npx tsc --init
import express from 'express';
import SocketIo from 'socket.io';
const app = express();
const server = app.listen(3000, () => {
console.log('Listening at port 3000');
});
const io = SocketIo(server);
io.on('connection', (socket) => {
console.log(`${socket.id} connected.`);
});
io.on('connect', (socket) => {
// sending to the client
socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
// sending to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
// sending to all clients in 'game' room except sender
socket.to('game').emit('nice game', "let's play a game");
// sending to all clients in 'game' room, including sender
io.in('game').emit('big-announcement', 'the game will start soon');
// sending to all connected clients
io.emit('an event sent to all connected clients');
}
socket.on('eventName', (msg) => {
console.log(msg);
});
Por padrão, o server expõe um client bundle em /socket.io/socket.io.js
io
será registrado como variável global:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
Se você não precisar disso, pode desabilitar no server:
import SocketIo from 'socket.io';
const io = SocketIo({
serveClient: false
});
npm install socket.io-client
import io from 'socket.io-client';
Do mesmo domínio:
const socket = io();
De um domínio diferente:
const socket = io('https://server-domain.com');
socket.on('serverEvent', (msg: string) => {
console.log(msg);
});
socket.emit('eventName', obj);
// same origin version
const socket = io('/admin');
// cross origin version
const socket = io('https://server-domain.com/admin');