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.
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.