简体   繁体   English

如何不断地将消息从 node.js 发送到我的前端

[英]How to constantly send message from a node js to my front end

How to constantly update my front end dashboard with new information from the back end.如何使用来自后端的新信息不断更新我的前端仪表板。 I have been searching for a solution online, but couldn't stumble on any.我一直在网上寻找解决方案,但找不到任何解决方案。

I already know how to send static variables with ejs, but I cant figure out how to update my front end with new messages from the server.我已经知道如何使用 ejs 发送 static 变量,但我不知道如何使用来自服务器的新消息更新我的前端。

I am working with express for the server and ejs for templating, plus server side java script.我正在使用用于服务器的 express 和用于模板的 ejs,以及服务器端 java 脚本。

I want to consonantly send messages to the user.我想一致地向用户发送消息。 Something like page 3 of 100......, 10 of 100..... and so forth.像第 3 页,共 100 页……,第 10 页,共 100 页……等等。 If you have experience with node Js, kindly help me out.如果您有使用 node Js 的经验,请帮助我。 Thanks.谢谢。

You could use Long pooling to solve your problem, Long pooling is,您可以使用 Long pooling 来解决您的问题,Long pooling 是,

  • A request is sent to the server一个请求被发送到服务器

  • The server doesn't close the connection until it has a message to send服务器在有消息要发送之前不会关闭连接

  • When a message appears – the server responds to the request with it当消息出现时——服务器用它响应请求

  • The browser makes a new request immediately.浏览器立即发出新请求。

The situation when the browser sent a request and has a pending connection with the server is standard for this method.浏览器发送请求并与服务器建立挂起连接的情况是此方法的标准情况。 Only when a message is delivered, the connection is reestablished.只有在传递消息时,才会重新建立连接。

If the connection is lost, because of, say, a.network error, the browser immediately sends a new request.A sketch of client-side subscribe function that makes long requests:如果连接丢失,例如由于网络错误,浏览器会立即发送一个新请求。客户端订阅 function 发出长请求的示意图:

async function subscribe() {
  let response = await fetch("/subscribe");

  if (response.status == 502) {
    // Status 502 is a connection timeout error,
    // may happen when the connection was pending for too long,
    // and the remote server or a proxy closed it
    // let's reconnect
    await subscribe();
  } else if (response.status != 200) {
    // An error - let's show it
    showMessage(response.statusText);
    // Reconnect in one second
    await new Promise(resolve => setTimeout(resolve, 1000));
    await subscribe();
  } else {
    // Get and show the message
    let message = await response.text();
    showMessage(message);
    // Call subscribe() again to get the next message
    await subscribe();
  }
}

subscribe();

Hope this hepls!希望这个hepls!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM