Socket.IO:服务器发出事件后未收到客户端确认

问题描述 投票:0回答:1

我正在使用 Socket.IO 从服务器向特定客户端发出事件。客户端已成功接收该事件,并且客户端处理数据没有任何错误。然而,即使客户端显式调用,服务器也不会收到确认回调

服务器端代码

async function emitData(
    socket: Socket,
    targetSocketId: string,
    event: configUpdate,
    data: any,
    callback: Function,
    mpu_id: string
) {
    console.log('Emitting event:', event, 'to socket ID:', targetSocketId);
    try {
        socket.to(targetSocketId).emit(event, data, async (acknowledgment: any) => {
        console.log('Acknowledgment received:', acknowledgment); 
            if (acknowledgment && acknowledgment.status === 'ok') {
                await updateSendToMpu(mpu_id);
                callback({ status: 'ok', message: `${event} successfully updated.` });
            } else {
                callback({
                   status: 'error',
                    message: acknowledgment
                        ? 'Client failed to acknowledge.'
                        : 'No acknowledgment received from client.',
                });
            }
        });
    } catch (error) {
        console.error('Error emitting data:', error);
        callback({ status: 'error', message: 'Failed to emit event.' });
    }
}

客户端代码

socket.on('configUpdate', async (data, callback = () => {}) => {
  console.log('Callback type:', typeof callback);
  try {
     if (typeof callback !== 'function') {
       console.error('Callback is not a function');
       return;
    }
    console.log('Received configuration update from server:', data);
    const entries = Object.entries(data);
    if (entries.length === 0) {
      console.warn('No configuration data provided.');
      callback({ status: 'ok', message: 'No configuration data to process.' });
      return;
    }
 
  callback({ status: 'ok', message: 'Configuration processed successfully.' });
    console.log('Configuration processed successfully.');
  } catch (error) {
    console.error('Error processing configuration update:', error);
    callback({ status: 'error', message: `Error processing data: ${error.message}` });
  }
});
```   from client side **console.log('Configuration processed successfully.');** is printing correctly on server side its shows **console.log('Acknowledgment received:', acknowledgment);**  
Could someone guide me on what might be causing this issue or suggest debugging steps? Any help is appreciated, as I’m new to Socket.IO.





The event name configUpdate matches between the server and client.
The client logs show the data is received and processed correctly.
I’ve confirmed the callback type is a function on the client side.
node.js sockets socket.io client-server socket.io-client
1个回答
0
投票

应该是以下原因造成的

  1. Socket.IO 版本兼容性:- 请确认服务器和客户端都使用兼容版本的 Socket.IO 并确保两者对齐例如: 在服务器上运行 npm list socket.io。 在客户端上运行 npm list socket.io-client
  2. 网络或中间件问题
© www.soinside.com 2019 - 2024. All rights reserved.