node.js - NodeJS 和 socket.io 聊天定制

标签 node.js socket.io

我有一个使用 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/

相关文章:

php - 通过 websocket 添加聊天到现有的 PHP Web 应用程序

node.js - 如何在Zend框架中使用Node.js和socket.io

django - 什么是与Django搭配使用的最佳socket.io服务器-gevent或tornadio2?

node.js - 使用 node.js 获取和设置正确的窗口位置

javascript - 如何在 botpress 自定义组件中获取 json 对象?

node.js - Node if语句执行顺序

node.js - Nginx HTTP 和 2 TCP,端口 80

javascript - 通过名称获取嵌套对象属性的更优雅的方法?

node.js - 使用 node.js 加密/解密密码

node.js + express + socket.io 无法将 javascript 文件加载到 index.html