我正在使用 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.
应该是以下原因造成的