Thread7
Thread7

Reputation: 1090

NodeJS and socket.io chat customization

I have a basic chat system working with NodeJS, express, and socket.io. Now I want to have the server insert the date into the chat stream every 5 seconds. Since this isn't initiated by the user, I am having trouble with the basic request. I am new to NodeJS and maybe it is just a syntax thing that I don't understand. Anyways, with this current code, the date only gets inserted after someone sends a chat message through. I want this to happen automatically on the server side. If no one is chatting, the date will still come through to the client every 5 seconds. My problem most likely stems from the comment section title: "How do I get my periodic timer in here..." Instead I am trying to insert it at the bottom where it says - "//***This section sends out the notification..." Do I structure the functions differently or something? Thanks in advance.

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

Here is the html in the browser - 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> 

Upvotes: 1

Views: 1527

Answers (1)

Brad Harris
Brad Harris

Reputation: 1520

It's much simpler than you're making it. You can just setInterval() to 5 seconds, and call io.sockets.emit(), which will send the message to all connected sockets.

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

Do this on line 18, and delete everything below there.

Upvotes: 4

Related Questions