🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

Como construir um aplicativo em tempo real com WebSockets e Node.js em 2026

⏱️7 min read  ·  1,447 words

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know. Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

mkdir realtime-app && cd realtime-app
npm init -y
npm install express socket.io ioredis cors

# Frontend dependencies
npm install -D vite

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

// server.js
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const Redis = require('ioredis');
const cors = require('cors');

const app    = express();
const server = createServer(app);
const io     = new Server(server, {
  cors: {
    origin:  "http://localhost:5173",   // Vite dev server
    methods: ["GET", "POST"]
  }
});

app.use(cors());
app.use(express.json());

// Redis Pub/Sub for multi-instance scaling
const pub = new Redis({ host: 'localhost', port: 6379 });
const sub = new Redis({ host: 'localhost', port: 6379 });

// ── Active users tracking ─────────────────────────────────
const activeUsers = new Map();  // socketId → { userId, username, room }

// ── Subscribe to Redis (messages from other server instances) ──
sub.subscribe('chat', 'notifications', (err, count) => {
  console.log(`Subscribed to ${count} Redis channels`);
});

sub.on('message', (channel, message) => {
  const data = JSON.parse(message);
  if (channel === 'chat') {
    io.to(data.room).emit('message', data);
  }
  if (channel === 'notifications') {
    io.to(data.userId).emit('notification', data);
  }
});

// ── Socket.io connection handler ──────────────────────────
io.on('connection', (socket) => {
  console.log(`Client connected: ${socket.id}`);

  // ── Authenticate ───────────────────────────────────────
  socket.on('authenticate', ({ userId, username }) => {
    activeUsers.set(socket.id, { userId, username });
    socket.join(userId);   // join personal room for direct notifications
    socket.emit('authenticated', { userId, socketId: socket.id });
    console.log(`User authenticated: ${username} (${userId})`);
  });

  // ── Join chat room ─────────────────────────────────────
  socket.on('join_room', ({ roomId }) => {
    const user = activeUsers.get(socket.id);
    if (!user) return socket.emit('error', 'Not authenticated');

    socket.join(roomId);
    activeUsers.set(socket.id, { ...user, room: roomId });

    // Notify others in room
    socket.to(roomId).emit('user_joined', {
      userId:   user.userId,
      username: user.username,
      roomId,
      timestamp: Date.now()
    });

    console.log(`${user.username} joined room: ${roomId}`);
  });

  // ── Send message ───────────────────────────────────────
  socket.on('send_message', async ({ roomId, content }) => {
    const user = activeUsers.get(socket.id);
    if (!user) return socket.emit('error', 'Not authenticated');

    const message = {
      id:        `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,
      userId:    user.userId,
      username:  user.username,
      content,
      room:      roomId,
      timestamp: Date.now()
    };

    // Publish to Redis so ALL server instances receive it
    pub.publish('chat', JSON.stringify(message));

    // TODO: persist to database here
    // await db.messages.create({ data: message });
  });

  // ── Typing indicator ───────────────────────────────────
  socket.on('typing', ({ roomId, isTyping }) => {
    const user = activeUsers.get(socket.id);
    if (!user) return;
    socket.to(roomId).emit('user_typing', {
      userId:   user.userId,
      username: user.username,
      isTyping
    });
  });

  // ── Disconnect ─────────────────────────────────────────
  socket.on('disconnect', () => {
    const user = activeUsers.get(socket.id);
    if (user?.room) {
      socket.to(user.room).emit('user_left', {
        userId:   user.userId,
        username: user.username
      });
    }
    activeUsers.delete(socket.id);
    console.log(`Client disconnected: ${socket.id}`);
  });
});

// ── REST API: send notification from backend ──────────────
app.post('/notify', (req, res) => {
  const { userId, type, message } = req.body;
  pub.publish('notifications', JSON.stringify({ userId, type, message, timestamp: Date.now() }));
  res.json({ ok: true });
});

server.listen(3001, () => console.log('Server running on port 3001'));

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

// hooks/useSocket.ts
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';

export function useSocket(userId: string, username: string) {
  const socket  = useRef<Socket | null>(null);
  const [connected, setConnected] = useState(false);
  const [messages, setMessages]   = useState<Message[]>([]);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [typingUsers, setTypingUsers]     = useState<Set<string>>(new Set());

  useEffect(() => {
    socket.current = io('http://localhost:3001');

    socket.current.on('connect', () => {
      setConnected(true);
      socket.current!.emit('authenticate', { userId, username });
    });

    socket.current.on('message', (msg: Message) => {
      setMessages(prev => [...prev, msg]);
    });

    socket.current.on('notification', (notif: Notification) => {
      setNotifications(prev => [notif, ...prev]);
    });

    socket.current.on('user_typing', ({ username: typer, isTyping }) => {
      setTypingUsers(prev => {
        const next = new Set(prev);
        isTyping ? next.add(typer) : next.delete(typer);
        return next;
      });
    });

    socket.current.on('disconnect', () => setConnected(false));

    return () => { socket.current?.disconnect(); };
  }, [userId, username]);

  const joinRoom  = (roomId: string) => socket.current?.emit('join_room', { roomId });
  const sendMessage = (roomId: string, content: string) =>
    socket.current?.emit('send_message', { roomId, content });
  const setTyping = (roomId: string, isTyping: boolean) =>
    socket.current?.emit('typing', { roomId, isTyping });

  return { connected, messages, notifications, typingUsers, joinRoom, sendMessage, setTyping };
}

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

# Run multiple instances
PORT=3001 node server.js &
PORT=3002 node server.js &
PORT=3003 node server.js &

# Nginx load balancer with sticky sessions (WebSocket requirement)
upstream websocket {
    ip_hash;  # sticky sessions - same client hits same server
    server localhost:3001;
    server localhost:3002;
    server localhost:3003;
}

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.
Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

Error 504 (Server Error)!!1504.That’s an error.There was an error. Please try again later.That’s all we know.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা