我的問題是什麼是發送數據到特定房間的特定客戶端的正確方法。我使用的插座IO和下面寫的代碼:如何發送數據到特定的客戶端在一個特定的房間與插座io
我用命令:
socket.to(socket.id).emit('change', {data})
但是客戶從來沒有得到這個命令。有人知道爲什麼
下面是我的代碼片段:
服務器代碼:
io.on('connection', function (socket) {
socket.on('channelJoin', function(channel){
socket.join(channel);
if(deltasByChannel[channel])
{
console.log("sending initial data to: "+socket.id);
socket.to(socket.id).emmit('change', deltasByChannel[channel]);
}
socket.on("change", function(delta){
console.log("channel: " + channel+" was edited!");
console.log(deltasByChannel[channel]);
deltasByChannel[channel] ? deltasByChannel[channel] = deltasByChannel[channel].concat(delta) : deltasByChannel[channel] = delta;
socket.broadcast.to(channel).emit('change', delta);
});
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
客戶端代碼:
var channel = window.location.pathname;
var socket = io.connect();
//Ace handlers
var sendUpdateData = function(e){
socket.emit("change", [e.data]);
};
socket.on('connect', function(){
socket.on("change", function(data){
console.log("change event received!");
editor.getSession().removeListener('change', sendUpdateData);
editor.getSession().getDocument().applyDeltas(data);
editor.getSession().on('change', sendUpdateData);
});
editor.getSession().on('change', sendUpdateData);
socket.emit('channelJoin', channel);
});
只是爲了避免混淆編輯器對象用於偵聽change事件好。它來自完全不同的庫(ace.js),與我的socket io問題無關。
下面是爲了更清楚,服務器代碼的另一個片段:
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function() {
console.log('listening on *:3000');
});
你能告訴你實例的'http'對象的代碼,和'io'對象連接到服務器,可能使用'聽'方法? – bencripps 2014-09-28 02:14:11
好吧,我把這部分的另一個片段。 – 2014-09-28 02:17:51
我假設'emmit'是一個錯字,而你真的使用'emit'? – bencripps 2014-09-28 02:22:54