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

查看:19
本文介绍了如何确保通过 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?

感谢您的回答!

推荐答案

您应该在定义事件处理程序时使用回调参数.

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".接下来检查客户端的控制台.它应该显示确定".这是确认信息.

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天全站免登陆