我有一个使用 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>
最佳答案
这比你做的要简单得多。您可以将 setInterval() 设置为 5 秒,然后调用 io.sockets.emit(),这会将消息发送到所有连接的套接字。
setInterval(function() {
io.sockets.emit('message', (new Date()).getTime());
}, 5000);
在第 18 行执行此操作,并删除下面的所有内容。
关于node.js - NodeJS 和 socket.io 聊天定制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961796/