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

查看:149
本文介绍了确认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 were the receiver will send another custom event as an acknowledge, 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天全站免登陆