is there a good way to save socket.io message history

后端 未结 1 1111
一向
一向 2021-02-06 17:52

I want to record socket.io message history, i.e. the contents of two users talked, for later use. Is there some socket.io built-in functions to realize this, or if not, what is

相关标签:
1条回答
  • 2021-02-06 18:30

    First of, you need some way to identify the users with a unique id that does not disappear when the user disconnects, like a username or an email address.

    All the messages in the conversation should then somehow be stored on the server, like in a "chat-object" for the conversation between the two users.

    Either periodically, when the user disconnects, or every time a the "chat-object" changes (eg. a new message is sent), save the "chat-object" in a database of any sort you like. You can use JSON to serialize the "chat-object", save it in any way you like (eg. a custom file, a mysql database, or whatever). To serialize an object, use the code below on the node server:

    var chatString = JSON.stringify(theChatObject);
    

    Save the string together with the two users' unique IDs. So when a new conversation is started between the same two people. You can just go to your file or database and retrieve the old chatobject, and unserialize it with the following code.

    var oldChat = JSON.parse(theRetrievedChatString);
    
    0 讨论(0)
提交回复
热议问题