前段时间我在一些在线游戏中使用了一种巧妙的方法,但是您还需要在服务器端进行更改!
第一个函数发送数据
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
}
所以现在只要你想为服务器发送一些数据并等待你简单的特定数据的响应:
sendData('man whats 1+1', function(data){console.log('server response:');console.log(data);});