gpt4 book ai didi

Node.js - 提供 index.html 文件以及提供 Web 套接字服务

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:25 25 4
gpt4 key购买 nike

我是 Node 和 Socket.io 的新手,并尝试运行以下代码。它旨在为 WebSocket 请求提供服务,但我想对其进行修改,使其也能提供静态内容,例如 index.html。

我的网络套接字代码如下:

var http        = require("http"),
sys = require("sys"),
io = require("socket.io"),
GlobTrie = require("glob-trie.js");

var Brokaw = {};

Brokaw.Server = function(port) {
var self = this;

// setup the basic HTTP server -- socket.io will wrap this
var server = http.createServer(function(req, res) {
// We have to respond with something, otherwise the connections hang :(
res.writeHead(404);
res.close();
});
server.listen(port);

this._io = io.listen(server, { "resource": "brokaw" });
this._trie = new GlobTrie();

this._io.on("connection", function(conn) {
new Brokaw.Server.Client(conn, self);
});
};

new Brokaw.Server(8080);

我提供index.html的代码如下:

// Hardcode *all* HTTP requests to this server to serve up index.html
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);
}
);

任何人都可以建议如何集成两者,即修改顶部代码以服务我的 index.html 文件吗?

感谢任何评论,我已经奋斗了很多小时了!

问候,本。

最佳答案

有一个例子,取自官方Socket.IO homepage :

服务器端:

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')

app.listen(80);

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) {
console.log(data);
});
});

客户端:

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

关于Node.js - 提供 index.html 文件以及提供 Web 套接字服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8465324/

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