我有一个使用 NodeJS、express 和 socket.io 的基本聊天系统。现在我想让服务器每 5 秒将日期插入到聊天流中。由于这不是由用户发起的,因此我在基本请求方面遇到了麻烦。我是 NodeJS 的新手,也许这只是我不理解的语法问题。无论如何,使用此当前代码,只有在有人发送聊天消息后才会插入日期。我希望这在服务器端自动发生。如果没有人聊天,日期仍将每 5 秒发送给客户端。我的问题很可能源于评论部分标题:“我如何在这里获得我的定期计时器......”相反,我试图将它插入到它说的底部 - “//***本部分发出通知...” 我是否以不同的方式构建功能或其他什么?提前致谢。
服务器.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>