在 Node.js 中实现服务器发送事件的简单方法? [英] Simple Way to Implement Server Sent Events in Node.js?

查看:46
本文介绍了在 Node.js 中实现服务器发送事件的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,似乎所有在 Node.js 中实现 SSE 的方法都是通过更复杂的代码,但似乎应该有一种更简单的方法来发送和接收 SSE.是否有任何 API 或模块可以简化此操作?

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 receive SSEs. Are there any APIs or modules that make this simpler?

推荐答案

你应该可以使用 Socket.io 做这样的事情.首先,您需要使用 npm install socket.io 安装它.从那里,在您的代码中,您将需要 var io = require(socket.io);

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);

你可以看到更深入的例子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});
});

客户端上的类似内容:

<script src="socket_src_file_path_here"></script>
<script>
  var socket = io('http://localhost');
  socket.on('EVENT_NAME', function (data) {
    console.log(data);
    //Do whatever you want with the data on the client
  });
</script>

这篇关于在 Node.js 中实现服务器发送事件的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆