Synchronous request with Websockets

前端 未结 5 2130
一生所求
一生所求 2020-12-30 04:04

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 r

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 04:48

    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 !

    1st make a function to send the data

    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');
        }
    }
    

    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);});
    

提交回复
热议问题