简体   繁体   English

使用 Websocket 与 express 和 Nodejs 不工作

[英]Using Websocket with express and Nodejs not working

I have this code which I am using for my express server.我有这段代码用于我的快递服务器。 The server works when I access the routes over http however when I try to connect to it over wss it doesnt work.当我通过 http 访问路由时服务器工作,但是当我尝试通过 wss 连接它时它不起作用。 What am I doing wrong?我究竟做错了什么?

const morgan = require("morgan");
const cors = require("cors");
const passport = require("passport");
const localStrategy = require("./auth/local");
const jwtStrategy = require("./auth/jwt");
const expressValidator = require("express-validator");
const config = require("./config");

const app = express();

const http = require("http").Server(app);
const io = require("socket.io")(http);

app.use(cors());
app.use(express.json());
app.use(expressValidator());
app.use(morgan("common"));
app.use(passport.initialize());

passport.use(localStrategy);
passport.use(jwtStrategy);

require("./routes")(app);

io.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});
io.on("connection", (socket) => {
  console.log("a user connected", socket);
});

http.listen(config.port);

module.exports = app;

Try using ws: in place of wss: for a quick fix.尝试使用ws:代替wss:进行快速修复。

wss: is the TLS-secured version of ws: , analogous to https: and http: . wss:ws: : 的 TLS 安全版本,类似于https:http: In fact, websocket connections to a server begin their lives as http / https connections.实际上,与服务器的 websocket 连接开始于 http / https 连接。 They're then "upgraded" to websocket connections by the websocket protocol.然后通过 websocket 协议将它们“升级”到 websocket 连接。

So, to get wss: to work on that server of yours, start by getting https: working for the express webserver part.因此,要获得wss:在您的服务器上工作,首先要获得https:为 express webserver 部分工作。 It's the https server behind express that will also handle the connections to be upgraded. Express 后面的 https 服务器也将处理要升级的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM