在Node.js上的相同地址处提供WebSocket和HTTP服务器 [英] Serve WebSocket and HTTP server at same address on Node.js
问题描述
我使用Node.js在端口8888上设置了 Websocket服务器 。我还有一个与Websocket后端(聊天服务器)交互的接口。
I have set up a Websocket server on port 8888, using Node.js. I also have an interface for that which interacts with the Websocket backend (chat server).
当使用浏览器访问服务器时,如何提供index.html(带有CSS / JS文件)?
How do I serve the index.html (with it's CSS/JS files) when the server is accessed using a browser?
推荐答案
如果您不想使用 socket.io
,但 websocket
包,您可以将它与快递,如下所示:
If you don't want to use socket.io
, but the websocket
package, you can use it in combination with Express like this:
// app.js
var WebSocketServer = require('websocket').server;
var express = require('express');
var app = express();
var server = app.listen(8888);
var wsServer = new WebSocketServer({ httpServer : server });
// this will make Express serve your static files
app.use(express.static(__dirname + '/public'));
// the rest of your code
wsServer.on('request', function(r) { ...
express.static
将负责提供您的HTML / CSS / JS文件。您传递的参数是目录这些文件所在的位置(在这种情况下,目录 public /
相对于 app.js
所在的位置)。
express.static
will take care of serving your HTML/CSS/JS files. The argument you pass is the directory where those files are located (in this case, the directory public/
relative to where app.js
is located).
这篇关于在Node.js上的相同地址处提供WebSocket和HTTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!