我想使用socket.io和node作为我的“推送通知功能”的层,所以我正在运行apache和node。
我的服务器(节点)上有以下代码
var app = require('http').createServer(handler)
, io = require('C:/path/to/file/socket.io').listen(app)
, fs = require('fs');
app.listen(8080);
function handler(req, res) {
console.log(req);
fs.readFile('C:/path/to/file/index.html',
function (err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('my event', function (msg) {
console.log("DATA!!!");
});
});
然后该页面由来自localhost的apache提供,没有8080端口
在客户端上我有以下代码:
var socket = io.connect('http://localhost:8080');
单击按钮时:
socket.emit('my event', {data:"some data"});
我在节点控制台上什么都没看到......为什么会这样?跨域问题?
更新 它在safari 5.1.5甚至IE 9上运行得很好,但不是在chrome(18.0.1025.151)或firefox(11.0)上......我错过了什么?
这是节点日志:
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 4944162402088095824
debug - setting request GET /socket.io/1/websocket/4944162402088095824
debug - set heartbeat interval for client 4944162402088095824
debug - client authorized for
debug - websocket writing 1::
debug - setting request GET /socket.io/1/xhr-polling/4944162402088095824?t=13
33977095905
debug - setting poll timeout
debug - discarding transport
debug - cleared heartbeat interval for client 4944162402088095824
答案 0 :(得分:3)
这应该可以正常工作,只需确保在index.html中有:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
另外,既然你是通过Apache服务你的页面,你真的不需要你的节点文件中的处理程序和http服务器。 这应该工作得很好:
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.on('my event', function (msg) {
console.log("DATA!!!");
});
});
和index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="utf-8">
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var socket = io.connect('http://localhost:8080');
$("#button").click(function() {
socket.emit('my event' ,"Hello World!");
})
})
</script>
</head>
<body>
<button type="button" id='button'>Send Message</button>
</body>
</html>
修改:这适用于Firefox和Chrome。