【发布时间】:2011-12-02 16:45:32
【问题描述】:
我正在寻找一种通过以下方式集成 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>
在这个例子中,当我转到 URL 中的 8080 端口时,我不得不使用 fs.readFile 。
有什么建议吗?谢了。
【问题讨论】:
-
尝试使用 nginx 而不是 apache,特别是如果您只想提供静态文件。 Apache 为每个请求启动一个新线程,这部分违背了使用节点的理念/原因。
标签: javascript node.js websocket socket.io