Drew Khoury
Drew Khoury

Reputation: 1390

How to send old messages with Websockets

I've got a working Websockets example, where clients receive messages from the server.

I'm not sure how I should send old messages to clients when they connect.

Example:

I'm wondering if there's any way clients can receive old messages (either all of them, or messages in the last 5 minutes would be acceptable).

I suspect I may have to capture this information myself, store it somewhere (like a database) and send the messages to new clients myself. Is that right, or am I missing something?

If anyone has pseudo code, or a link to an example of how others have implemented this, that would be handy.

Upvotes: 12

Views: 5981

Answers (2)

Leo Nomdedeu
Leo Nomdedeu

Reputation: 338

You could do something like this:

  1. Each message should have an id -> muid (Message Unique ID)
  2. Each time a client send s a message, it gets an ACK from the server along with the muid for the sent message.
  3. Each time a new message is received in the server side, a muid is assigned, sent with the ACK and also sent with the message to every connected user. This way the view will be able to present, for every user, the same sequence at some point in the time.
  4. Each time a new user connects it sends the last muid it has received so the server knows where this user stopped receiving messages. The server could then send as many old messages as you want, depending on the kind of storage you implement:
    1. Full history: I would recommend a database storage with proper indexing
    2. Last N messages: Depending on the size of N you could simply store the last N messages in a fixed size Array and send them, all or the needed chunk, on each reconnection. Keep in mind that this will consume memory so, storing last 1024 messages for 1024 different chats would eat quite a bit of memory, specially if messages are of unlimited size.

Hope it helps

Upvotes: 8

Jack Daniel's
Jack Daniel's

Reputation: 2613

You will have to capture it by your own and store it on server... once user connects you will have to name that data to all connected clients and the messages which you have stored back to the user who has connected. So, you will have to code to broadcast the data to users

By the way what are you using server side? (Node, Erlang , etc)

You can check following link if you are using node.js

http://martinsikora.com/nodejs-and-websocket-simple-chat-tutorial

Upvotes: 6

Related Questions