Express and WebSocket listening on the same port

后端 未结 2 939
半阙折子戏
半阙折子戏 2020-12-13 06:40

I have an app.js which is used to trigger two events when some POST data are received:

  1. Insert POST data into a database
  2. Send a message to a client us
2条回答
  •  悲&欢浪女
    2020-12-13 06:50

    Based on your code and comments, here's a super simple example of how it would work together.

    First, the http-server.js - a typical express app, except that we do not start the server with 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;
    

    Now, the ws-server.js example, where we create the WSS server from a node native http.createServer(). Now, note that this is where we import the app, and give this native http.createServer the app instance to use.

    Start the app with PORT=8080 node ws-server.js :

    (Note you're launching the second, socket related, file (ws-server) not the first, http related, file (http-server).)

    '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}`);
    });
    

    Finally, this sample index.html will work by creating both a POST and a Socket "request" and display the response:

    
    
      WS example
    
    
    
      

    Socket message response:

    
      

    POST message response:

    
      
    
    
    

    Note you'll need a quite recent browser, one that has both WebSocket and fetch APIs for this client side part, but it's irrelevant anyway, it just gives you the gist of it.

提交回复
热议问题