Express and WebSocket listening on the same port

后端 未结 2 940
半阙折子戏
半阙折子戏 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 07:11

    http and ws on the same port 80, "Amazing Zlatko Method™."

    You'll have a file, say main.js, with

     var app = express()
    

    and many lines of express code.

    It is perfectly OK to have as much middleware as you want in the usual way with no changes.

    var app = express()
    app.use(session(session_options))
    app.use(passport.initialize())
    app.use(passport.session())
    app.use('/static', express.static('static'))
    // etc etc
    app.get ...
    app.get ...
    app.post ...
    app.post ...
    

    Normally at the end of that file you would

     app.listen(80, (err) => { ... })
    

    Delete that.

     //app.listen(80, (err) => { ... })
    

    No other changes in the express app file.

    In your websocket file, say multiplayer.js, you would normally have

    const WebSocket = require('ws');
    const wss = new WebSocket.Server({
        port: 9999,
        perMessageDeflate: false
    })
    

    In fact, change to

    const WebSocket = require('ws');
    /*const wss = new WebSocket.Server({
        port: 2828,
        perMessageDeflate: false
    });*/
    let WSServer = WebSocket.Server;
    let server = require('http').createServer();
    let app = require('./main'); // note, that's your main.js file above
    let wss = new WSServer({
      server: server,
      perMessageDeflate: false
    })
    server.on('request', app);
    

    And at the end of that file

    server.listen(80, function() {
        console.log(`Amazing Zlatko Method™ combo server on 80`);
    });
    

    Note! - launch the 'multiplayer.js' file (not 'main.js').

    It works perfectly. Amazing stuff.

提交回复
热议问题