简体   繁体   中英

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:

  • Each client supplies their name when they connect
  • The server responds with "[name] just connected" (to all clients)
  • Any new clients would NOT get these messages

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.

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

You could do something like this:

  1. Each message should have an id -> muid ( Message Unique ID )
  2. Each time a client send sa 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM