私は少し前にオンラインゲームで使った方法はありますが、サーバー側でも変更する必要があります。
第一は、要求を処理するときに、サーバ側では、あなたが応答
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);
}
}
で、クライアントにcmd_idを送るべきデータ
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');
}
}
を送信する機能を作成し、他のすべてのタイプのリターンを処理する関数を作成します。
socketRecieveData(data){
//whatever processing you might need
}
so simpサーバーのデータを送信して、単純なデータの応答を待つ場合は、
sendData('man whats 1+1', function(data){console.log('server response:');console.log(data);});
非同期の機能は使用できません。忙しい待っている、とJavaScriptはそれをサポートしていません。なぜそうしたいのですか?約束を見てください。 – Bergi
実際に@Bergiできます。下の私の答えを見てください。シンプルなキューを作成してください。その例ではビジー待機しません:) –
@RonanDejhero:いいえ、あなたの関数は同期していません。すべてのソケットリスナーが必要とするので、非同期コールバックを使用します。 – Bergi