S
S
ski282020-11-22 10:22:08
Node.js
ski28, 2020-11-22 10:22:08

What is the correct way to send a response to socket.io in response to a user request?

Good afternoon. Google didn't find the answer. More precisely, I found that such a structure is not correct. Therefore, I want to learn from experts how to properly organize what I want.

System: nodejs , expressjs , socket.io , ejs , mysql , apache2
Task. You need to give a random prize to the user.
How it's solved now: via ajax.
Problem . The site starts to slow down when there are 250-300 online users at the same time. I store some rendered pages in a variable, but that didn't help much either. Previously slowed down at 150 online. Also, the cache gives cloudflare, which also saves a lot.

How do I want to load the site.
Take out the bonus in js and connect it to the main socket
. How did I manage to do this.

User

//Запрос на получение
socket.emit('bunus' , 'start');
//Ждём результат
socket.on( 'result' , (data) => {
       console.log(data);
});

On server

//Запрос пользователя
socket.on('bunus', function ( data ) {
  let r = {};
       r.data = data;  
             //socket.id для ответа именно этому пользователю
       r.user = socket.id;
             //id пользователя для проверки авторизован или нет
       r.user_id = socket.handshake.session.userId; 
  io.emit( 'new_bunus' , r );
});
// Ответ от бонус js
socket.on('new_result', function ( data ) {
  io.to(data.user).emit( 'result', data); 
});


bonus js

const socket = io.connect(config.connection_type + '://localhost:' + config.PORT , {
    secure: true,
    reconnect: true,
    rejectUnauthorized: false
});
socket.on('connect', function() {
  console.log('connect Успешно подключились к SocketIO! bonus.js : '+process.pid);
});
//Ждём запрос на выдачу бонуса
socket.on('new_bunus' , function ( data ) {
    data.bonus = "рандомный бонус";
    socket.emit('new_result', data );
});


That's how it works. But to me it's a great design. There is a callback in socket.io and I would like to write through it.

User
//Запрос на получение
socket.emit('bunus' , 'start'  , (data)=>{
    console.log(data);
});

On server

//Запрос пользователя
socket.on('bunus', function ( data , cb) {
  let r = {};
       r.data = data;  
             //id пользователя для проверки авторизован или нет
       r.user_id = socket.handshake.session.userId; 
  io.emit( 'new_bunus' , r  ,  (result)=>{
              cb(result);
        });
});


bonus js

const socket = io.connect(config.connection_type + '://localhost:' + config.PORT , {
    secure: true,
    reconnect: true,
    rejectUnauthorized: false
});
socket.on('connect', function() {
  console.log('connect Успешно подключились к SocketIO! bonus.js : '+process.pid);
});
//Ждём запрос на выдачу бонуса
socket.on('new_bunus' , function ( data , cb) {
    data.bonus = "рандомный бонус";
    cb(data);
});


Everything seems to be logical. But I get the error "Callbacks are not supported when broadcasting" ((. Please tell me how to write correctly, so that it would be without unnecessary.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2020-11-22
@vshvydky

Socket.io out of the box makes it possible to use room.
Room usage flow:
1. The client connects to the socket, the user's token is checked, and the user's id is obtained from it.
2. The current socket joins the room with the user ID (read the doc about join).
3. Messages to the user are sent as to(roomName).emit...
What profit do we have?
1. It doesn't matter how many pages a user has open, you don't have to manually map which socket to which user and how many sockets are open for one user.
2. Message routing goes to the library code level.
3. Other users do not receive messages that are addressed to a specific user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question