ExpressJS 路由 + Websockets - 共享端口

Kar*_*ric 2 https port websocket node.js express

我有一个带有 websockets 的 httpsexpressjs 服务器(使用“ws”包)。据我了解套接字和端口,我应该能够在 websocket 连接旁边添加一条路由。主要用例是使服务器可以卷曲(我在网上看到的 ws curl 请求都不起作用。)

不幸的是我只有 1 个端口可用于服务器和 Websocket。如何设置以便应用程序服务器都可以侦听同一端口?

我看到一些关于 SO 的评论表明它可以完成,但没有代码示例,或者它适用于非常不同的包。

我正在使用“ws”包: https: //www.npmjs.com/package/ws

const port = 8888;
const http = require('http');
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();
      app.use( express.static('public') );
      app.get('/curl', (req, res) => res.send('Hello World')).listen( port );

const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });

httpsServer.listen( port, function listening(){
    console.log( 'listening on ' + port );
});
Run Code Online (Sandbox Code Playgroud)

目前,我收到“EADDRINUSE”错误,因为我对两个“服务器”使用相同的端口。

跟进

  • 如果其他服务器正在监听,Express 应用程序也不需要监听。
  • 要卷曲 https,您必须提供证书详细信息,或使用“-k”(不安全)方法。

jfr*_*d00 6

您的代码显示您尝试在同一端口上启动两个服务器。

此行创建一个新的 http 服务器并尝试在端口 8888 上启动它:

app.get('/curl', (req, res) => res.send('Hello World')).listen( port );
Run Code Online (Sandbox Code Playgroud)

这些行创建一个新的 https 服务器并尝试在端口 8888 上启动它。

const httpsServer = https.createServer( credentials, app );

httpsServer.listen( port, function listening(){
    console.log( 'listening on ' + port );
});
Run Code Online (Sandbox Code Playgroud)

你不能这样做。如果您只想要一个同时适用于您的 Web 请求和 webSocket(一种常见的处理方法)的 https 服务器,请将您的代码更改为:

const port = 8888;
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();

app.use( express.static('public') );
app.get('/curl', (req, res) => res.send('Hello World'));

const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });

httpsServer.listen( port, function listening(){
    console.log( 'listening on ' + port );
});
Run Code Online (Sandbox Code Playgroud)

它只是删除了对对象.listen(port)进行操作的 ,app因为这将创建一个 http 服务器并在 8888 端口上启动它。