0

I'm developing a chat with django.socketio. I would like to keep track of the messages sent on a socket so that I can render it when a new user comes. I want him to see the messages sent before he arrived.

My code is very simple:

template:

      <script>
      var url = window.location.pathname.split('/');
      var id = url[3];
      var socket = new io.Socket();
      socket.connect();
      socket.on('connect', function(context){
      socket.subscribe('channel-' + id)  
      });


      socket.on('message', function(data){
      $('.try').prepend('<div> '+val+' </div>');
       });


    function send(){
    var val = $('#text').val();
    data = val
    socket.send(data);
   };
    </script>

html:

  <form id="form" onsubmit="send(); return false">
  <input type="text" id="text">
  <input type="submit" value="Send">
  </form>

  <div class="try"> </div>

events.py:

  @events.on_message(channel='^channel-')
    def messages(request, socket, context, message):
    socket.send_and_broadcast_channel(message)

In this simple chat, with different channels, I would like to keep track of the messages sent ( for each channel ) and render it when the user first connect.

I'm looking for hints on how to do that.

Thank you very much.

Juliette Dupuis
  • 1,027
  • 2
  • 13
  • 22
  • You should upgrade to gevent-socketio though.. I think django-socketio is deprecated in favor of the former – abourget Nov 30 '12 at 13:12

1 Answers1

1

Just create a table for the messages and make sure one of the columns is the chatroom name or id so you can query last 10 messages on subscribing to chatroom.

So when rendering the page, you get the last messages from database and the next ones come from socket.

If you don't want the messages saved for long just truncate the table periodically to cleanup.

Dslayer
  • 1,101
  • 14
  • 17
  • Ok, thank you for this answer. I was wondering if for that kind of task I have to use a specific database. Do you think I can do that with MySq if there are a lot of messages? – Juliette Dupuis Nov 21 '12 at 12:13
  • i don't think the number of messages should be the most important thing to make a decision on db choice. The most important is what other tasks you're going to use database for and what other db techs can offer. But for just this purpose, any of them is good enough. – Dslayer Nov 21 '12 at 15:37