socket.io在循环中发出,直到客户端响应?

时间:2017-03-29 07:24:42

标签: node.js socket.io

我想每隔X秒向客户端发送一条消息,直到客户点击按钮并确认收到。

关于如何实现这一目标的任何想法? Node的新手,但我希望我能用Node和Sockets.io完成这项工作。

提前感谢任何见解或帮助,让我朝着正确的方向前进。

2 个答案:

答案 0 :(得分:1)

我认为实现这一目标的最佳方法是创建一个扩展" vanilla" Node.js事件类。您需要首先要求它:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

https://nodejs.org/api/events.html

一旦你上课了,你需要做的是创建一个子进程,为此,你可以参考这里的官方文档:

https://nodejs.org/api/child_process.html

在此过程中,您可以创建循环并通过套接字发送消息。扩展事件类的目的是能够创建一个Inside事件发射,您可以监听以检测特定事件(例如套接字关闭或您想要跟踪的任何事件)

我希望这能回答你的问题。

答案 1 :(得分:0)

这是一个简单的设置,只是为了让您了解如何操作:

节点服务器(非常基本,只有socket.io,没有别的):

const io = require('socket.io')(3000);
const interval = 1000;
io.on('connection', function (socket) {
    console.log(socket.id + ' has connected');
    var foo = setInterval (function () {
        socket.emit('foo');
    }, interval);   
    socket.on('confirmed', function () {
        console.log('confirmation received from ' + socket.id);
        clearInterval(foo);
    });     
});
console.log('socket.io server started at port 3000');

index.html(在浏览器中打开它,看看会发生什么):

<!doctype html>
<html>
  <head>
    <title>Testing socket.io</title>
  </head>
  <body>
    <button id="button">Confirm</button>
    <p id="socket">waiting...</p>
    <p id="alert">foos counter: </p>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script>
        var socket = io("http://localhost:3000");
        var counter;
        socket.on('connect', function() {
          counter = 0;
          document.getElementById("socket").innerHTML = "connected";
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("confirmed");
          });
      });
      socket.on('foo', function() {
          counter++;
          document.getElementById("alert").innerHTML = "foos counter: " + counter;
      });
    </script>
  </body>
</html>