1) webpack-dev-server 只能代理 websocket 连接,仅此而已。
devServer: {
proxy: {
'/websocket': {
target: 'ws://[address]:[port]',
ws: true // important
},
}
}
2) 无需将服务器拆分为 HTTP 和 WS 部分。要在 javascript 中同时使用两者,您可以使用 express-ws。这在其他语言中也可用(Spring 支持它,Django 也支持)。
下面的代码片段提供静态文件(如 webpack-dev-server),同时为您提供 websocket 接口。
const express = require('express');
const expressWs = require('express-ws');
const app = express();
expressWs(app);
//serve static files, 'public/index.html' will be served as '/'
app.use(express.static('public'));
// normal express.js handler for HTTP GET
app.get('/hello', function(req, res, next){
res.send('hello');
});
// websocket handler
app.ws('/websocket', function(ws, req) {
ws.on('message', function(msg) {
ws.send(msg);
});
});
app.listen(3000);
3) 同样,webpack-dev-server 只为您的静态文件提供服务,并且没有 WS 等价物。您知道在请求 GET /file.txt HTTP 1.1 时会发生什么。 WS 只是一个传输协议。
奖励:socket.io 已普遍失宠,因为所有主流浏览器现在都支持 websockets 并且不需要后备行为。