对 socket.io 自定义事件的确认 [英] Acknowledgment for socket.io custom event

查看:17
本文介绍了对 socket.io 自定义事件的确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来确认 socket.emit 调用.

I am looking for a method to acknowledge a socket.emit call.

socket.emit('message', msg);

我见过一种机制,接收者会发送另一个自定义事件作为确认,但这会在我的聊天应用程序中添加数千个传输.请建议一个有效的方法.

I have seen a mechanism where the receiver would send another custom event as an acknowledgement, but this would add thousands of transports in my chat application. Please advice an efficient method.

推荐答案

emit 方法的第三个参数接受一个回调,该回调将传递给服务器,以便您可以使用任何您想要的数据进行确认调用.这实际上非常方便,并且省去了配对呼叫响应事件的工作.

The third argument to the emit method accepts a callback that will be passed to the server so that you can call in acknowledgement with any data you wish. It's actually really convenient and saves the effort of having paired call-response events.

我正在用我刚刚测试过的一些代码更新我的答案.

I'm updating my answer with some code that I just tested.

首先在服务器端:

   io.sockets.on('connection', function (sock) {

    console.log('Connected client');
    sock.emit('connected', {
        connected: 'Yay!'
    });

    // the client passes 'callback' as a function. When we invoke the callback on the server
    // the code on the client side will run
    sock.on('testmessage', function (data, callback) {
        console.log('Socket (server-side): received message:', data);
        var responseData = {
            string1: 'I like ',
            string2: 'bananas ',
            string3: ' dude!'
        };
        //console.log('connection data:', evData);
        callback(responseData);
    });
});

客户端:

console.log('starting connection...');
var socket = io.connect('http://localhost:3000');
socket.on('error', function (evData) {
    console.error('Connection Error:', evData);
});
// 'connected' is our custom message that let's us know the user is connected
socket.on('connected', function (data) {
    console.log('Socket connected (client side):', data);

    // Now that we are connected let's send our test call with callback
    socket.emit('testmessage', {
        payload: 'let us see if this worketh'
    }, function (responseData) {
        console.log('Callback called with data:', responseData);
    });
});

这篇关于对 socket.io 自定义事件的确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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