Multiple Topic SOCKET.IO Connection

Discussão em 'Angular' iniciado por Akhil Gorantala, Setembro 30, 2024.

  1. So i have User1, 2, 3, 4. every user has there own topic and subscribe to it in an angular application, and iam publishing the data to that topic via a post api, with that specific user jwt. But its not publishing the data to the user topic.

    const express = require('express');
    const http = require('http');
    const socketIo = require('socket.io');
    const cors = require('cors');

    const app = express();
    const server = http.createServer(app);
    const io = socketIo(server, {
    cors: {
    origin: "http://localhost:4200", // Replace with your frontend URL
    methods: ["GET", "POST"],
    allowedHeaders: ["auth-key"],
    credentials: true
    }
    });

    // Enable CORS for all routes
    app.use(cors());

    // Middleware to check for auth key
    io.use((socket, next) => {
    const authKey = socket.handshake.headers['auth-key'];
    if (authKey === 'your-secret-key') {
    return next();
    }
    return next(new Error('Authentication error'));
    });

    app.get('/verify/:channel', (req, res) => {
    const { channel } = req.params;
    if (['channel1', 'channel2', 'channel3'].includes(channel)) {
    res.status(200).send({ message: 'Channel is valid' });
    } else {
    res.status(400).send({ message: 'Invalid channel' });
    }
    });

    io.on('connection', (socket) => {
    console.log('New client connected');

    socket.on('subscribe', (channel) => {
    console.log(`Client subscribed to ${channel}`);
    socket.join(channel);
    });

    socket.on('publish', ({ channel, message }) => {
    console.log(`Publishing message to ${channel}: ${message}`);
    socket.emit(channel, message);
    });

    socket.on('disconnect', () => {
    console.log('Client disconnected');
    });
    });

    const PORT = process.env.PORT || 4000;
    server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

    Continue reading...

Compartilhe esta Página