【发布时间】:2015-05-16 10:10:41
【问题描述】:
我正在尝试使用 nodejs、express 和 socket.io 为画廊构建一个遥控器。
结构如下
/index.js
/public/screen.html
/screen.js
/remote.html
/remote.js
这个想法是在remote.html 上显示一个图片库,选择一个并使用socket.io 将选定的索引发送到screen.html。
到目前为止,我的代码如下所示:
index.js
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
app.use(express.static('public'));
server.listen(8080, function(){
// setup image gallery and stuff...
connectToServer();
});
remote.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function showImage (index){ //called by events
console.log('selected incdex: ' + index);
if(socket != null) {
socket.emit('selection', {id: index});
};
}
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newRemote', 'new remote connected');
console.log('emitted welcome');
socket.on('newScreen', function (data) {
console.log(data);
});
});
}
screen.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newScreen', { name: name });
socket.on('newRemote', function (data) {
console.log(data);
});
});
};
当以node index.js 开头时,我明白了
listening on *:8080
当加载屏幕或 remote.html 时,我得到了
debug - client authorized
info - handshake authorized MwtGFRCZamcyKkUpK5_W
在我看来:以某种方式建立了连接,但是:
没有消息在两端发送/接收 连接事件的日志不会打印到控制台
知道为什么什么都没发生吗?
【问题讨论】:
标签: javascript node.js sockets express socket.io