gpt4 book ai didi

javascript - 正确捕获 Socket.io 的错误

转载 作者:行者123 更新时间:2023-12-02 16:42:50 31 4
gpt4 key购买 nike

我正在构建一个简单的聊天。我使用 websocket lib socket.io 因为它有一个很好的服务器/客户端实现。

我的客户端使用移动设备,因此网络连接非常不稳定。我读过一些有关确认函数的内容,这些函数可以通过发出传递,以便在套接字“事务”完成后执行代码。但在此基础上构建错误处理将非常丑陋。

我还阅读了有关捕获错误的 .on('error' 实现。

这里的问题是:如何区分发送失败的消息(.emit)和暂时丢失的套接字连接。我不关心丢失套接字连接,因为我将其设置为在丢失后重新连接。

我希望我的情况清楚了。提前致谢。

编辑:

我正在寻找的是客户端类似的东西:

socket.on('error', function(data){
alert(data.emitData.msg+' could not be sent: '+data.emitID);
});

与此同时,我自己将开始仔细研究 API

最佳答案

消息确认已覆盖here in the socket.io docs 。以下是该文档的相关部分:

Sometimes, you might want to get a callback when the client confirmed the message reception.

To do this, simply pass a function as the last parameter of .send or .emit. What’s more, when you use .emit, the acknowledgement is done by you, which means you can also pass data along:

Server (app.js)

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});

Client (index.html)

<script>
var socket = io(); // TIP: io() with no args does auto-discovery
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
</script>

并且,此处显示另一个示例:Acknowledgment for socket.io custom event

关于javascript - 正确捕获 Socket.io 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359868/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com