前端的侦听器在后端侦听器上侦听 [英] Listener in front end to listen on back end listener

查看:82
本文介绍了前端的侦听器在后端侦听器上侦听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找答案,但是找不到任何好的方法.我在NodeJS内置的cloudant上有一个侦听器.因此,当cloudant更新时,会调用我代码中的一个函数.我的问题是,这些数据应在前端应用程序中作为实时数据提供.如果我将侦听器放在API端点/中间件中,除非得到前端的请求,否则它将不会被调用?

I’ve been looking for an answer regarding this but can’t find anything good. I have a listener on cloudant which I have built in NodeJS. So when cloudant gets updated a function in my code gets called. My problem is that this data should be available as live data in a front end application. If I put the listener in an API-endpoint/middleware it won’t get called unless it gets a request from front end I guess?

所以我的问题是:如何在后端创建一个侦听器,以便在出现Cloudant变化时可以将数据发送到前端?基本上,我希望前端的监听器可以监听后端的监听器.

So my question is: How can I create a listener in backend which can send data to front end whenever a change in cloudant appears? Basically I want a listener in front end to listen on a listener in back end.

推荐答案

因此,您正在寻找能够从服务器向客户端发送或推送"数据的功能.这样做的典型方法是使用webSocket或socket.io连接.客户端连接到服务器并创建与服务器的持久连接.从那时起,服务器可以随时通过该连接向客户端发送数据.然后,客户端在该连接上创建一个侦听器,以便它知道何时有传入数据,然后可以根据该数据采取相应的操作.

So, what you're looking for is the ability to send or "push" data from server to client. The typical way of doing this is with a webSocket or socket.io connection. The client connects to the server and creates a lasting connection to the server. From then on, the server can just send data to the client over that connection whenever it wants to. The client then creates a listener on that connection so it will know when there is incoming data and it can then act accordingly based on the data.

webSocket是启用此类功能的标准内置浏览器.socket.io是在webSocket连接之上构建的附加客户端和服务器层,它添加了许多有用的功能,例如,如果连接断开,将自动重新连接,它是一个JSON消息定义层,因此您不必定义自己的数据格式等...

webSocket is the standard built-into browsers that enables this type of function. socket.io is an additional client and server layer built on top of a webSocket connection that adds a lot of useful features such as auto-reconnection if the connection dies, a JSON message definition layer so you don't have to define your own data format, etc...

这通常是这样的:

  1. 服务器初始化时,它将为传入的socket.io连接创建一个socket.io侦听器.webSocket/socket.io用于共享"用于加载网页的同一Web服务器,因此您不需要其他服务器或端口.
  2. 在浏览器中加载页面时,该页面中的某些Javascript会创建与服务器的socket.io连接.
  3. 然后,客户端为希望对其执行操作的任何消息设置侦听器.
  4. 同时,当服务器收到要发送给客户端的内容时,它既可以将数据发送给所有当前连接的客户端,也可以仅将其发送给一个特定的客户端.
  5. 然后,客户端的事件侦听器将触发并接收数据.
  6. 然后,客户可以决定要对数据做什么,通常在当前显示的页面中插入一些内容.
  7. 当浏览器切换到另一个网页时,socket.io连接将自动断开.

socket.io文档有一些示例代码客户端和服务器都向您展示如何编程.

The socket.io documentation has several pieces of sample code for both client and server to show you how it is programmed.

这篇关于前端的侦听器在后端侦听器上侦听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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