Node.js服务器在启动时挂起 |Websocket 连接失败

Node.js server hanging on startup | Websocket connection failed

提问人:Mark Miller 提问时间:12/29/2021 最后编辑:Mark Miller 更新时间:12/29/2021 访问量:917

问:

所以我正在尝试使用 node.js express 托管一个 Web 应用程序,但我server.js似乎挂在使用 .在我的package.json文件中,它调用并且一切正常启动,但我的网站不会部署到本地主机供我查看。我有一种感觉,这要么与我的位置有关,要么可能与我从客户端创建请求的方式有关,因为我是后端的新手,所以真的深入到这个。npm startnode server.jscss/index.htmlindex.html

//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = '/public/index.html';
const express = require('express')



var server = express();
console.log(__dirname)
server.use(express.static(__dirname + "/public"));
server.get('public/index.html', function(req, res, next) {
      res.sendFile(__dirname + INDEX);
  });
server.listen(PORT);


//2.) Create a websocket server

const { Server } = require('ws');
const wss = new Server({ server });


//3.) Handle connections

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});


//4.) Boradcast updates
setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);
console.log('Server started at http://localhost:' + PORT);

这是我在下面index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <title>am i sheep</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>

  <div>
    <span>
      <h3> Am I Sheep<h3>
    </span>
  </div>

  <div>
  </div>
  <div>
        <input type="file" id="fileID" hidden></input>
        <label for='fileID'>select image</label>
  </div>

  <div>
    <h1 id='server-time'>current time</h1>
    <script>
    var HOST = location.origin.replace(/^http/, 'ws')
    var ws = new WebSocket(HOST);
    var el;

    ws.onmessage = function (event) {
      el = document.getElementById('server-time');
      el.innerHTML = 'Server time: ' + event.data;
    };
    </script>
  </div>
</body>
</html>

更新:

所以现在似乎弹出的问题是 所以在客户端和服务器之间的握手之间发生了错误WebSocket connection to 'ws://localhost:2525/' failedvar ws = new WebSocket(HOST);

node.js Express 服务器端

评论

0赞 BGPHiJACK 12/29/2021
听起来很简单,哪些端口正在访问您的网站想要使用的端口?
0赞 BGPHiJACK 12/29/2021
听起来像是环境设置问题、另一个应用程序共享端口或其他问题。
0赞 Mark Miller 12/29/2021
我专门检查并检查了哪些端口正在使用中,并使用此端口终止了 PID。如果我在它启动并挂起后运行它,但是如果我运行服务器然后关闭并再次启动它,它将创建一个错误,因为端口正在使用中。我主要是对为什么网站不会部署到本地主机感到困惑。我什至使用开始和结束计时器来检查server.js文件的每个部分是否正常工作,它似乎都可以正常工作,但仍然一无所获

答:

1赞 Muhammed Rahif 12/29/2021 #1

server.js

//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = "/public/index.html";
const express = require("express");
const { createServer } = require("http");

const app = express();
const httpServer = createServer(app);

// Static files
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res, next) {
  res.sendFile(__dirname + INDEX);
});

//2.) Create a websocket server
const { Server } = require("ws");
const wss = new Server({ server: httpServer });

//3.) Handle connections
wss.on("connection", ws => {
  console.log("Client connected");
  ws.on("close", () => console.log("Client disconnected"));
});

//4.) Boradcast updates
setInterval(() => {
  wss.clients.forEach(client => {
    client.send(new Date().toTimeString());
  });
}, 1000);

httpServer.listen(PORT, () => console.log("Server started at http://localhost:" + PORT));

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>am i sheep</title>
    <link rel="stylesheet" href="css/style.css" type="text/css">
</head>

<body>

    <div>
        <span>
            <h3> Am I Sheep<h3>
        </span>
    </div>

    <div>
    </div>
    <div>
        <input type="file" id="fileID" hidden></input>
        <label for='fileID'>select image</label>
    </div>

    <div>
        <h1 id='server-time'>current time</h1>
        <script>
            var HOST = location.origin.replace(/^http/, 'ws')
            var ws = new WebSocket(HOST);
            var el;

            ws.onopen = function () {
                alert('Connection Open');
            };

            ws.onerror = function (error) {
                alert('Error');
            };

            ws.onmessage = function (event) {
                el = document.getElementById('server-time');
                el.innerHTML = 'Server time: ' + event.data;
            };
        </script>
    </div>
</body>

</html>

评论

0赞 Mark Miller 12/29/2021
它最初可以工作,但我尝试修改我的server.js代码以使用我的自定义style.css,然后它就停止工作了。
0赞 Mark Miller 12/29/2021
因此,每当我使用'''npm start''时,它都会正常运行server.js文件,但它不会在localhost:2525上显示index.html
0赞 Muhammed Rahif 12/29/2021
那么你在浏览器中打开了它吗?
0赞 Mark Miller 12/29/2021
我尝试在浏览器中打开它,但它不会加载任何内容。我在 ubuntu 中运行我的环境,所以我从命令行完成了所有设置,然后去检查 localhost:2525,浏览器中不会显示任何内容
0赞 Muhammed Rahif 12/29/2021
server.get('public/index.html', ...请查看此行 ?如果你想完全打开它,你需要把它编辑成。server.jslocalhost:2525/server.get('/', ...