0

Web 套接字连接错误

我的服务器有问题。它使用expressexpress-ws用于网络套接字。问题是该服务器在本地主机上运行良好。ssh但是当我在(参见localhost.run )的帮助下运行它并通过另一台计算机(通过 Chrome)的给定链接访问该站点时,Web 套接字没有打开,并且下一个错误显示在控制台中

main.js:12 WebSocket connection to 'ws://localhost:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

即使我添加了certkey服务器连接。PS该站点也加载了,只是套接字不起作用。


这是 server.js 代码:

"use strict";
const fs = require("fs");

const credentials = {
  key: fs.readFileSync("./key.pem"),
  cert: fs.readFileSync("./cert.pem")
};

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const https = require("https");

const PORT = process.env.PORT || 3000;

app.use(express.static(__dirname + "/public/Messenger"));
app.use(express.static(__dirname + "/public/Login"));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const server = new https.createServer(credentials);

const expressWs = require("express-ws")(app, server);//if i take the 
//second argument (server) away, it works fine on localhost:3000, but 
//with this it fires the error:

//WebSocket connection to 'ws://localhost:3000/' failed: Connection 
//closed before receiving a handshake response

const routes = require("./MVC/Router/router.js"); //importing route
routes(app);

app.listen(PORT, () => {
  console.log("listening on port " + PORT);
});

这是router.js:

   "use strict";
module.exports = function(app) {
  const database = require("../Controller/controller.js");

  // database Routes
  app.route("/").get(database.loadPage);

  app.route("/login").get(database.loginPageLoad);

  app
    .route("/signIn")
    .get(database.signInPageLoad)
    .post(database.signIn);

  app
    .route("/submitLogin")
    .post(database.loginSubmit)
    .get(database.showUsers);

  app.ws("/", database.sendmsg);
};

它将处理流程重定向到 controller.js 的下一部分:

const CLIENTS = [];
let counter = 0;

exports.sendmsg = (ws, req) => {
  console.log(cache.get("lorem"));
  ws.on("message", msg => {
    if (msg === "connected") {
      console.log("connected");
      CLIENTS.push([ws, counter]);
      ws.send(JSON.stringify({ counter }));
      counter++;
    } else if (JSON.parse(msg).msg && JSON.parse(msg).ID) {
      CLIENTS.forEach(box => {
        if (box[1] === msg.ID) {
          console.log(`user ${box[1]} is closed`);
          box.push("closed");
          box[0].close();
        } else {
          return;
        }
      });
    } else {
      sendAll(msg);
    }
    ws.on("close", () => {
      console.log("disconnected");
      ws.close();
    });
  });
};

function sendAll(message) {
  for (let i = 0; i < CLIENTS.length; i++) {
    if (CLIENTS[i][0].readyState === 1) {
      CLIENTS[i][0].send(message);
    }
  }
}

最后一段代码就是它在服务器上的作用,不用太在意。问题是当我从另一台计算机输入链接时,网络套接字没有打开。我该如何解决?

4

0 回答 0