Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

socket.io - can't send messages to a specific room in a socket #3650

Closed
iman2420 opened this issue Sep 25, 2020 · 3 comments
Closed

socket.io - can't send messages to a specific room in a socket #3650

iman2420 opened this issue Sep 25, 2020 · 3 comments

Comments

@iman2420
Copy link

I'm trying to set up my node server to update all the connected clients with new information in real-time. When I run the code below, the io.sockets.on('connection') callback is fired constantly, flooding the console with the message Client connected!, and the front-end is not being updated from socket.emit(). What am I doing wrong?

const port = process.env.PORT || 3000;
const app = require('http').createServer(function (req, res) {
});
app.listen(port);
const io = require('socket.io').listen(app, () => {
console.log('Server listening at port %d %s', port);
});

const pool = require('./socketMySql');
let numUsers = 0;
const users = {};


io.on('connection', (socket) => {
let addedUser = false;
socket.on('joinToClass', (classroom_id) => {
    const isArray = (classroom_id.toString().startsWith("["));
    if (isArray)
        classroom_id = JSON.parse(classroom_id);
    socket.join(parseInt(classroom_id), function () {
        let rooms = Object.keys(socket.rooms);
        console.log("joinToClass " + classroom_id + " rooms " + rooms);
    });
});

socket.on('leaveTheClass', (classroom_id) => {
    const isArray = (classroom_id.toString().startsWith("["));
    if (isArray)
        classroom_id = JSON.parse(classroom_id);
    socket.leave(classroom_id, function () {
        console.log("Socket now leave The Class " + classroom_id);
    });
});

// when the client emits 'add user', this listens and executes
socket.on('add user', (data) => {
    if (addedUser) return;
    data = JSON.parse(data);
    // we store the username in the socket session for this client
    socket.username = data.name;
    socket.family = data.family;
    socket.id = data.id;
    ++numUsers;
    addedUser = true;
    users[socket.id] = data.id;       
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
        username: socket.username,
        numUsers: numUsers,
        userId: socket.id
    });
});

// when the client emits 'typing', we broadcast it to others
socket.on('typing', async (data) => {
    data = JSON.parse(data);
    const classroomId = data.classroom_id;
    const typingData = {
        classroom_id: classroomId,
        userId: data.userId,
        exam_id: data.exam_id
    };
    io.sockets.in(parseInt(classroomId)).emit('typing', typingData);   //<==   NOT WORK
});

// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', (data) => {
    data = JSON.parse(data);
    const classroomId = data.classroom_id;
    io.sockets.in(classroomId).emit('stop typing', { //<==   NOT WORK
        classroom_id: classroomId,
        userId: data.userId,
        exam_id: data.exam_id
    });      
});

// when the user disconnects.. perform this
socket.on('disconnect', () => {
    if (addedUser) {
        --numUsers;
        delete users[socket.id];      
        // echo globally that this client has left
        socket.broadcast.emit('user left', {
            username: socket.username,
            numUsers: numUsers,
            userId: socket.id
        });
    }
});
//just added
socket.on("error", (err) => {
        console.log("Caught flash policy server socket error: " + err.stack);
    }
)
});

In client side first call add user event when user come online.

When the user selects their class, event joinToClass is called to perform operation socket.join.

Event typing is called when the user is taking the exam, which I want to let the other class members know is taking the exam.

@Nibbler999
Copy link
Contributor

socket.id is used internally by socket.io, you shouldn't overwrite it.

@joaohenriquepda
Copy link

I have same problem with versions:
"socket.io": "^2.3.0"
"socket.io-redis": "^5.4.0"

@iman2420
Copy link
Author

@Nibbler999 You save my week. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants