一尘不染

Express和WebSocket在同一端口上侦听

node.js

我有一个app.js,用于在接收到一些POST数据时触发两个事件:

  1. 将POST数据插入数据库
  2. 使用WebSocket向客户端发送消息

这是 app.js (仅重要的 行)

var express = require('express');
var bodyParser = require('body-parser');
var server = require('./server');

var app = express();
var port = process.env.PORT || 3000;

app.post('/server', server);

app.listen(port, function(){
  console.log('Slack bot listening');
});

这是 server.js (仅重要的 行)

var db = require('./DB');
var WebSocketServer = require('ws').Server;

var insertData = function(req, res){

    var wss = new WebSocketServer({server: server});
    console.log('WebSocketServer created');
    wss.on('connection', function(wss){
        wss.send(JSON.stringify('Socket open'));
    });
    wss.on('close', function(){
        console.log('WebServerSocket has been closed');
    });
};

module.exports = insertData;

我想要实现的是以侦听应用程序相同端口的方式设置WebSocketServer。我考虑过将 服务器 var从 app.js 传递到
server.js, 但是

  1. 我认为这不是一个优雅的方法
  2. 我不知道该怎么做

你们有什么感想?


阅读 260

收藏
2020-07-07

共1个答案

一尘不染

根据您的代码和注释,这是一个如何一起工作的超简单示例。

首先, http-server.js -一个典型的快递应用程序,除了我们不使用以下命令启动服务器app.listen()

'use strict';

let fs = require('fs');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');

app.use(bodyParser.json());

// Let's create the regular HTTP request and response
app.get('/', function(req, res) {

  console.log('Get index');
  fs.createReadStream('./index.html')
  .pipe(res);
});

app.post('/', function(req, res) {

  let message = req.body.message;
  console.log('Regular POST message: ', message);
  return res.json({

    answer: 42
  });
});

module.exports = app;

现在,在该 ws-server.js
示例中,我们从一个native节点创建WSS服务器http.createServer()。现在,请注意,这是我们导入应用程序的地方,并为该本地http.createServer提供了要使用的应用程序实例。

使用以下命令启动应用程序PORT=8080 node ws-server.js

'use strict';

let WSServer = require('ws').Server;
let server = require('http').createServer();
let app = require('./http-server');

// Create web socket server on top of a regular http server
let wss = new WSServer({

  server: server
});

// Also mount the app here
server.on('request', app);

wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {

    console.log(`received: ${message}`);

    ws.send(JSON.stringify({

      answer: 42
    }));
  });
});


server.listen(process.env.PORT, function() {

  console.log(`http/ws server listening on ${process.env.PORT}`);
});

最后,此示例 index.html 将通过创建POST和套接字“请求”并显示响应来工作:

<html>
<head>
  <title>WS example</title>
</head>

<body>
  <h2>Socket message response: </h2>
  <pre id="response"></pre>
  <hr/>
  <h2>POST message response: </h2>
  <pre id="post-response"></pre>
  <script>

  // Extremely simplified here, no error handling or anything
document.body.onload = function() {

    'use strict';

  // First the socket requesta
  function socketExample() {
    console.log('Creating socket');
    let socket = new WebSocket('ws://localhost:8080/');
    socket.onopen = function() {

      console.log('Socket open.');
      socket.send(JSON.stringify({message: 'What is the meaning of life, the universe and everything?'}));
      console.log('Message sent.')
    };
    socket.onmessage = function(message) {

      console.log('Socket server message', message);
      let data = JSON.parse(message.data);
      document.getElementById('response').innerHTML = JSON.stringify(data, null, 2);
    };
  }

  // Now the simple POST demo
  function postExample() {

    console.log('Creating regular POST message');

    fetch('/', {  
      method: 'post',  
      headers: {  
        "Content-type": "application/json"  
      },  
      body: JSON.stringify({message: 'What is the meaning of post-life, the universe and everything?'})  
    })
    .then(response => response.json())  
    .then(function (data) {

      console.log('POST response:', data);
      document.getElementById('post-response').innerHTML = JSON.stringify(data, null, 2);   
    })  
    .catch(function (error) {  
      console.log('Request failed', error);  
    });   
  }

  // Call them both;

  socketExample();
  postExample();
}
  </script>
</body>
</html>

请注意,您将需要一种新的浏览器,该浏览器同时具有此客户端部分的WebSocket和fetch API,但是无论如何它都无关紧要,只是给您了要点。

2020-07-07