我正在寻找一种将Node.js + Socket.io + Apache集成的方法, 具体为:
- 我希望Apache继续提供HTML/JS文件。
- 我希望Node.js在8080端口上监听连接。类似于这样:
var util = require("util"),
app = require('http').createServer(handler),
io = require('/socket.io').listen(app),
fs = require('fs'),
os = require('os'),
url = require('url');
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
socket.emit('ok 1', { hello: 'world' });
});
socket.on('clientMSG', function (data) {
socket.emit('ok 2', { hello: 'world' });
});
});
如果我访问连接到这个服务器的HTML,则可以正常工作,但是我需要前往mydomian.com:8080/index.html。 我想要的是能够前往mydomian.com/index.html,并能够打开套接字连接:
<script>
var socket = io.connect('http://mydomain.com', {port: 8080});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data from the client' });
});
socket.on('connect', function (data) {
console.log("connect");
});
socket.on('disconnect', function (data) {
console.log("disconnect");
});
//call this function when a button is clicked
function sendMSG()
{
console.log("sendMSG");
socket.emit('clientMSG', { msg: 'non-scheduled message from client' });
}
</script>
在这个例子中,我不得不使用fs.readFile,因为当我访问URL中的端口8080时,它不起作用。
有什么建议吗?谢谢。