有没有保存socket.io消息历史的好方法 [英] is there a good way to save socket.io message history

查看:46
本文介绍了有没有保存socket.io消息历史的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录socket.io消息历史,即两个用户交谈的内容,以备后用.有没有socket.io内置的函数来实现这个,或者如果没有,有什么好的实现方式?

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 a good way to realize it?

推荐答案

首先,您需要一些方法来识别具有在用户断开连接时不会消失的唯一 ID(例如用户名或电子邮件地址)的用户.

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.

定期地,当用户断开连接时,或者每次聊天对象"发生变化(例如发送新消息)时,将聊天对象"保存在您喜欢的任何类型的数据库中.您可以使用 JSON 来序列化聊天对象",以您喜欢的任何方式保存它(例如,自定义文件、mysql 数据库或其他任何方式).要序列化对象,请在节点服务器上使用以下代码:

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);

将字符串与两个用户的唯一 ID 一起保存.因此,当相同的两个人之间开始新的对话时.您可以直接转到您的文件或数据库并检索旧的聊天对象,然后使用以下代码对其进行反序列化.

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);

这篇关于有没有保存socket.io消息历史的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆