Simple Way to Implement Server Sent Events in Node.js?

前端 未结 6 1293
南方客
南方客 2021-01-31 06:11

I\'ve looked around and it seems as if all the ways to implement SSEs in Node.js are through more complex code, but it seems like there should be an easier way to send and recei

6条回答
  •  离开以前
    2021-01-31 06:42

    You should be able to do such a thing using Socket.io. First, you will need to install it with npm install socket.io. From there, in your code you will want to have var io = require(socket.io);

    You can see more in-depth examples given by Socket.IO

    You could use something like this on the server:

    var express = require('express');
    var app = express();
    var server = require('http').createServer(app);
    var io = require('../..')(server);
    var port = process.env.PORT || 3000;
    
    server.listen(port, function () {
      console.log('Server listening at port ' + port);
    });
    
    app.use(express.static(__dirname + '/public'));
    
    io.on('connection', function (socket) {
        socket.emit('EVENT_NAME', {data});
    });
    

    And something like this on the client:

    
    
    

提交回复
热议问题