Reputation: 15
I am developing a website which, among other things, allows users to chat in real time with one another (similar to Facebook chat). Messages are stored in MySQL table messages
, which contains ID of the message, sender ID, receiver ID and time.
When user A is chatting with user B, I get all their messages by SQL statement SELECT * FROM messages WHERE (senderID='userA' AND receiverID='userB') OR (senderId='userB' AND receiverID='userA')
. This statement retrieves all the messages between user A and user B.
When chat is opened, I send an AJAX request every second (should it be less/more?) to check if there are any new messages between these two users in the database.
My questions are:
Upvotes: 0
Views: 657
Reputation: 22989
You should really use WebSockets for this but if you really want to go with polling this is how you could do it:
Your system should hold Conversations, Users or Participants and Messages.
When John starts a conversation for the 1st time with Mary, you create a new Conversation, with a unique conversation_id
. The Participants to that conversation are Mary and John.
When a user first opens a past Conversation, you SELECT * FROM messages WHERE conversation_id = 'xyz'
.
From then on when John sends a message to Mary you simply INSERT
that message in your database.
When Mary sends the next polling signal she includes in her message the last message_id
she received. This allows you to SELECT * FROM messages WHERE message_id > 115 AND conversation_id = xyz
.
Mary then appends to her existing list of messages the new messages.
This assumes that message_id
is an auto incremented column.
Other pointers:
Upvotes: 3