Web套接字在其他计算机上无法打开

时间:2019-02-11 21:06:10

标签: node.js express websocket server ws

Web soket连接错误

我的服务器出现问题。它为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。附言该网站也加载了,只是套接字不起作用。


这是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);
    }
  }
}

最后一段代码就是它在服务器上所做的事情,不必太在意。问题是,当我从另一台计算机输入链接时,Web套接字无法打开。我该怎么解决?

0 个答案:

没有答案