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

我想每X秒发送一条消息给客户端,直到客户点击一个button并确认收到。

任何想法如何我可以做到这一点? 新的节点,但我希望我可以用Node和Sockets.io做到这一点。

提前感谢任何见解或帮助让我在正确的方向。

我认为最好的方法是创build一个扩展“vanilla”Node.js事件类的新类。 您将需要先这样要求:

const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} 

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

一旦你有了课程,你需要做的是创build一个subprocess,这样做,你可以参考这里的官方文档:

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

在这个过程中,你可以创build你的循环并通过套接字发送消息。 扩展事件类的目标是能够创build一个Inside事件发射,您可以侦听特定的事件(比如套接字closures或任何您想要跟踪的事件)

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

这是一个简单的设置,只是为了让你知道如何做到这一点:

节点服务器(非常基本,只有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>