使用nodejs我將數據流式傳輸到客戶端/瀏覽器,並且沒有任何問題地列出它們。我想要做的是通過點擊它們將一些ID發送回服務器。無論如何,這裏是我的代碼。我希望你能告訴我在這種情況下我做錯了什麼。使用node.js上的socket.on方法從瀏覽器獲取數據
服務器端
var socketServer = io.listen(server);
socketServer.set('log level', 1); //don't log all emits etc
socketServer.sockets.on('connection', function(socket) {
console.log('New connection logged');
socketServer.sockets.emit('data', t.globalState);
});
//This is not working!
//I tried to put it in different places, no changes!
socketServer.sockets.on('hello', function(data) {
console.log('Hello!');
});
socketServer.sockets.on('close', function(socket) {
console.log('socketServer has closed');
});
var t = new conwit(config.conwit);
t.openStream = function() {
console.log('Opening Stream');
t.createStream();
};
t.createStream = function() {
t.stream('statuses/filter', {
track: t.globalState.tags,
language: config.language
}, function(stream) {
stream.on('data', t.emitT);
stream.on('error', function(error) {
console.log("My error: ", error);
setTimeout(function() {
t.openStream();
}, 30000);
});
});
};
t.emitT = function (data) {
console.log(' receiving');
if (data.text !== undefined) {
socketServer.sockets.emit('data', data);
}
};
t.openStream();
return t;
};
瀏覽器端
TM.socket.on('data', function(msg) {
alert('News from server: ' + msg); //this works
TM.socket.emit('hello', {msg:'Hello server'}); //this doesn't work!
});
$('#send').on('click', function(event) {
event.preventDefault();
TM.socket.emit('hello', { //this doesn't work
rF: "foo",
rT: "zazz",
ea: "limk"
});
});
沒有錯誤/兩側日誌消息。
這就像一個魅力。我錯過了socketServer.sockets.on中的** socket **變量('connection',function(** socket **)),並且yes ** config.conwit **正確傳遞。 – hayzem 2014-11-23 10:41:06