gpt4 book ai didi

javascript - Node.js + Socket.io + Apache

转载 作者:数据小太阳 更新时间:2023-10-29 04:56:40 25 4
gpt4 key购买 nike

我正在寻找一种通过以下方式集成 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 将无法工作。

有什么建议吗?谢谢。

最佳答案

从 Apache 端口 80 提供静态内容,并通过端口 8080 上的 Socket.IO 服务器提供动态/数据内容。您不需要 app = require('http').createServer(handler) 在你的 Socket.IO 应用中

Apache 端口 80 |--------------|客户 |------------| Socket.IO端口8080

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});

socket.on('clientMSG', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});

socket.on('disconnect', function () {
sockets.emit('user disconnected');
});
});

关于javascript - Node.js + Socket.io + Apache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7682338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com