如何确保已通过socket.io收到消息给客户端? [英] How to be sure that message via socket.io has been received to the client?

查看:789
本文介绍了如何确保已通过socket.io收到消息给客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查已通过 socket.io 库发送的消息已收到客户端。
socket.io中是否有特殊方法?

How to check that message sent with socket.io library has been received to the client. Is there special method for it in socket.io?

感谢您的回答!

推荐答案

您应该在定义事件处理程序时使用callback参数。

You should use the callback parameter while defining the event handler.

典型的实现方式如下:

客户端

var socket = io.connect('http://localhost');
socket.emit('set', 'is_it_ok', function (response) {
    console.log(response);
});

服务器端

io.sockets.on('connection', function (socket) {
    socket.on('set', function (status, callback) {
        console.log(status);
        callback('ok');
    });
});

现在检查服务器端的控制台。它应该显示'is_it_ok'。接下来检查客户端的控制台。它应该显示'ok'。这是确认消息。

Now check the console on the server side. It should display 'is_it_ok'. Next check console on client side. It should display 'ok'. That's the confirmation message.

socket.io连接本质上是持久的。以下内置函数允许您根据连接状态采取操作。

A socket.io connection is essentially persistent. The following in-built functions let you take action based on the state of the connection.

socket.on('disconnect', function() {} ); // wait for reconnect
socket.on('reconnect', function() {} ); // connection restored  
socket.on('reconnecting', function(nextRetry) {} ); //trying to reconnect
socket.on('reconnect_failed', function() { console.log("Reconnect failed"); });

使用上面显示的回调选项实际上是以下两个步骤的组合:

Using the callback option shown above is effectively a combination of the following two steps:

socket.emit('callback', 'ok') // happens immediately

和客户端

socket.on('callback', function(data) {
    console.log(data);
});

所以你不需要使用计时器。回调立即运行,除非连接具有以下任何状态 - 断开连接,重新连接,重新连接失败。

So you don't need to use a timer. The callback runs immediately except if the connection has any of the following states - 'disconnect', 'reconnecting', 'reconnect_failed'.

这篇关于如何确保已通过socket.io收到消息给客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆