Skip to content

Instantly share code, notes, and snippets.

@rodrigogonn
Last active April 16, 2024 00:56
Show Gist options
  • Save rodrigogonn/abeee2ab655334c1ca7c976a673fca64 to your computer and use it in GitHub Desktop.
Save rodrigogonn/abeee2ab655334c1ca7c976a673fca64 to your computer and use it in GitHub Desktop.
Utilizando Socket IO com Typescript

Socket IO com Typescript

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)

representation

Server Side

Instalação

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

Utilizando com express

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.`);
});

Emitindo eventos

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

Capturando eventos

socket.on('eventName', (msg) => {
  console.log(msg);
});

Client Side

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
});

Instalando com NPM

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');

Capturando e emitindo eventos no client side

socket.on('serverEvent', (msg: string) => {
  console.log(msg);
});
socket.emit('eventName', obj);

Conectando a um namespace customizado

// same origin version
const socket = io('/admin');
// cross origin version
const socket = io('https://server-domain.com/admin');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment