Tôi đang tìm cách tích hợp Node.js + Socket.io + Apache theo cách sau: Tôi muốn apache tiếp tục phục vụ các tệp HTML/JS. Tôi muốn Node.js để lắng nghe kết nối trên cổng 8080. Một cái gì đó như thế này:Node.js + Socket.io + Apache
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' });
});
});
nếu tôi truy cập vào một HTML mà kết nối đến máy chủ này, nó hoạt động, nhưng tôi cần phải đi đến mydomian.com:8080 /index.html. Điều tôi muốn là có thể truy cập mydomian.com/index.html. và có thể mở một kết nối socket:
<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>
Trong ví dụ này, tôi đã phải sử dụng fs.readFile công việc sẽ không khi tôi đi đến cổng 8080 trong URL.
Mọi đề xuất? Tks.
Hãy thử nginx thay vì apache, đặc biệt nếu bạn chỉ muốn phân phối các tệp tĩnh. Apache bắt đầu một chuỗi mới cho mọi yêu cầu mà một phần phản đối triết lý/lý do sử dụng nút. – badunk