使用Websockets进行同步请求 [英] Synchronous request with Websockets

查看:59
本文介绍了使用Websockets进行同步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在websockets上从服务器发送和接收消息。我需要编写一个函数,将数据发送到服务器并等待服务器的响应,然后作为函数的结果返回。

I can send and receive messages from server on websockets. I need to write a function that will send data to the server and is awaiting a response from the server and then return it as a result of a function.

发送:

ws.send('my_message_to_server');

收到(这是一个事件):

Receive (it's a event):

ws.bind('message', function(message) {
console.log(message);
});

我的功能:

function request(message){
ws.send(message);
    //How wait for receive???
    return response;
}


推荐答案

我使用的方式很简洁不久前在一些在线游戏中,你也需要在服务器端更改内容!

There's a neat way I used in some online game a while ago, but you will need to change stuff on the server side as well !

第一个发送数据的功能

var socketQueueId = 0;
var socketQueue = {};

function sendData(data, onReturnFunction){
    socketQueueId++;
    if (typeof(returnFunc) == 'function'){
        // the 'i_' prefix is a good way to force string indices, believe me you'll want that in case your server side doesn't care and mixes both like PHP might do
        socketQueue['i_'+socketQueueId] = onReturnFunction;
    }
    jsonData = JSON.stringify({'cmd_id':socketQueueId, 'json_data':data});
    try{
        webSocket.send(jsonData);
        console.log('Sent');
    }catch(e){
        console.log('Sending failed ... .disconnected failed');
    }
}

然后在服务器端,处理请求时,你应该使用响应将cmd_id发送回客户端

Then in the server side, when processing the request, you should send the cmd_id back to the client with the response

webSocket.onmessage = function(e) {

    try{
        data = JSON.parse(e.data);
    }catch(er){
        console.log('socket parse error: '+e.data);
    }

    if (typeof(data['cmd_id']) != 'undefined' && typeof(socketQueue['i_'+data['cmd_id']]) == 'function'){
        execFunc = socketQueue['i_'+data['cmd_id']];
        execFunc(data['result']);
        delete socketQueue['i_'+data['cmd_id']]; // to free up memory.. and it is IMPORTANT thanks  Le Droid for the reminder
        return;
    }else{
        socketRecieveData(e.data);
    }
}

并创建一个函数来处理所有其他类型的退货:

and create a function to handle all other types of returns:

socketRecieveData(data){
    //whatever processing you might need
}

所以现在只需要为服务器发送一些数据并等待特定数据的响应就可以了:

so now simply if you want to send some data for the server and wait for response for that specific data you simple do:

sendData('man whats 1+1', function(data){console.log('server response:');console.log(data);});

这篇关于使用Websockets进行同步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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