当前位置: 首页 > 面试题库 >

Express和WebSocket在同一端口上侦听

钱旻
2023-03-14
问题内容

我有一个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. 我不知道该怎么做

你们有什么感想?


问题答案:

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

首先, 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,但是无论如何它都无关紧要,只是给您了要点。



 类似资料:
  • 我想用Rust,Hyper和WebSocket-RS编写一个Web服务器。webserver必须能够在同一端口上处理http请求和websocket请求。我使用了正式示例(:https://github.com/cyderize/rust-websocket/blob/master/examples/async-server.rs),并尝试对其进行修改。我的想法是改变错误处理。如果客户机的请求是一

  • 我有一个现有的在线商店应用程序在前端创建了React和我正在尝试整合STRIPE作为支付方法使用NODE express在后端。我希望在同一个端口上启动它们,我尝试使用package.json中的代理,并将index.html作为静态文件提供服务,但它不起作用。 我确实将index.html作为静态文件提供,但它似乎除了HTML之外不读取任何其他内容。下面是我的代码: server.js 在pac

  • 问题内容: 我有多个Node应用程序(在Express框架上构建)。 现在,我将它们这样放置- 现在,我想在同一端口(例如8080)上运行这3个应用程序。那可能吗 ? 需要注意的一件事是,每个应用都有类似的通用路线- 基本上,我想这样做,就像您可以使用Apache / PHP设置一样。 因此,当您拥有LAMP堆栈时- 您可以通过-作为其他应用轻松访问它们- 问题答案: 您可以使用:

  • 问题内容: 在ExpressJS的第三个版本中, express.createServer() 更改为 express(), 此更改使得很难在同一端口上绑定socket.io。也许有人可以找到明智的决定。 现在,这不起作用: 我当前的工作流程:https : //gist.github.com/3596852 问题答案: 它在socket.io github页面上进行了描述(如@Golo在您的评论

  • 我试图拦截同一视图上的拖动事件以及双击事件,这样,如果用户双击同一视图,我可以将视图拖动到放置位置或打开对话框。问题在于使用SimpleOnGestureListener拦截MotionEvent时。设置View后的ACTION_DOWN事件。DragShadowBuilder(视图),永远不会调用onDoubleTap。关于如何允许拖动和双击视图,有什么想法吗?我想有一种可能是取消这个视图。在M