NodeJS和socket.io聊天自定义

我有一个使用NodeJS,express和socket.io的基本聊天系统。 现在我想让服务器每隔5秒将聊天的date插入到聊天stream中。 由于这不是由用户发起的,所以我在基本要求上遇到了麻烦。 我是NodeJS的新手,也许这只是一个我不明白的语法。 无论如何,使用这个当前的代码,date只有在有人发送聊天消息后才会被插入。 我希望这在服务器端自动发生。 如果没有人在聊天,那么date仍然会每隔5秒到达客户端。 我的问题很可能来自评论部分标题:“我如何得到我的周期性计时器在这里…”而是我试图插入它的底部,它说 – “/ / ***这部分发出通知…“我是否有不同的function? 提前致谢。

Server.js

var express = require('express'), app = express() , http = require('http') , server = http.createServer(app) , io = require('socket.io').listen(server); // listen for new web clients: server.listen(8080); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); app.get('/sio/socket.io.js', function (req, res) { res.sendfile('/root/nodejs/node-v0.10.0/node_modules/socket.io/lib/socket.io.js'); }); //How do I get my periodic timer in here so it can send the date every 5 seconds? io.sockets.on('connection', function (socket) { socket.on('sendMessage', function (data) { socket.broadcast.emit('message', data); socket.emit('message', { text: '<strong>'+data.text+'</strong>' }); }); }); // Periodic Running var coolerInterval = function(func, interval, triggerOnceEvery) { var startTime = new Date().getTime(), nextTick = startTime, count = 0; triggerOnceEvery = triggerOnceEvery || 1; var internalInterval = function() { nextTick += interval; count++; if(count == triggerOnceEvery) { func(); count = 0; } setTimeout(internalInterval, nextTick - new Date().getTime()); }; internalInterval(); }; coolerInterval(function() { showdate = new Date().getTime(); console.log( showdate ); //Go ahead and send a notification to everyone. //***This section sends out the notification that a pick was made io.sockets.on('connection', function (socket) { socket.on('sendMessage', function (data) { socket.broadcast.emit('message', showdate); }); }); //***End sending out notification. }, 1000, 5); //End Periodic 

这里是浏览器中的html – index.html

 <html> <body> <script src="/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $(document).ready(function () { var socket = io.connect('http://dev.mysite.com:8080'); socket.on('message', function (data) { $('#chat').append(data.text + '<br />'); }); $('#send').click(function () { socket.emit('sendMessage', { text: $('#text').val() }); $('text').val(''); }); }); </script> <div id="chat" style="width: 500px; height: 300px; border: 1px solid black"> </div> <input type="text" name="text" id="text"> <input type="button" name="send" id="send" value="send"> </body> </html> 

这比你做的简单得多。 您可以将setInterval()设置为5秒,然后调用io.sockets.emit() ,它会将消息发送到所有连接的套接字。

 setInterval(function() { io.sockets.emit('message', (new Date()).getTime()); }, 5000); 

在第18行这样做,并删除下面的所有内容。