前段时间我在一些在线游戏中使用了一种简洁的方式,但是您还需要更改服务器端的东西!
1日做一个函数来发送数据
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回客户端的响应
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);
}
}
和创建一个函数来处理所有其他类型的回报:
socketRecieveData(data){
//whatever processing you might need
}
so now simp LY,如果你想发送一些数据服务器并等待响应你简单做,具体的数据:
sendData('man whats 1+1', function(data){console.log('server response:');console.log(data);});
你不能做的东西异步同步功能。忙碌的等待是糟糕的,JavaScript不支持它。你为什么想要这样做?看看承诺。 – Bergi
@Bergi其实你可以。看看下面的答案。只是创建一个简单的队列,没有在这个例子中等待:) –
@RonanDejhero:不,你的功能不同步。它确实使用异步回调,因为每个套接字侦听器都需要。 – Bergi