使用signalR在SQL数据库中存储聊天对话 [英] Storing chat conversations in sql database using signalR

查看:247
本文介绍了使用signalR在SQL数据库中存储聊天对话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个类库,其中包含针对这些情况的通用方法:

I'm developing a class library that contains generic methods for these scenarios:

  • 实时支持聊天(与许多管理员和来宾进行一对一的私人文本聊天)
  • 拥有许多用户的房间,您可以在其中发送广播和私人消息

上面的这两个功能已经实现,现在我的应用程序必须保存消息.

These two features above are already implemented and now it's necessary for my application to save messages.

我的问题是,将聊天对话存储在SQL数据库中的最佳方法是什么?

My question is, what is the best way to store chat conversations in a SQL database:

  1. 每次单击发送时,都会在数据库中插入消息吗?

  1. Everytime I click send, I insert the message in the database?

为每个用户创建一个列表,每当我单击发送"时,该消息就会保存在发送该消息的用户的列表中.然后,如果用户断开连接,我将遍历消息列表,并针对每条消息将所有消息插入db中.

Create a List for each user and everytime I click send, the message is saved on the list of the user who sent the message. Then if a user disconnects, I'm going to iterate the list of messages and for each message insert all of them in the db.

还有其他解决方案吗?

我现在正在做的事情如下.我的Hub类中有此方法:

What I'm doing now is the following. I have this method which is located on my Hub class:

public void saveMessagetoDB(string userName, string message)
{
    var ctx = new TestEntities1();

    var msg = new tbl_Conversation {Msg = message};
    ctx.tbl_Conversation.Add(msg); 
    ctx.SaveChanges();           
}

我这样在客户端HTML文件中将此方法称为saveMessagetoDB:

I call this method saveMessagetoDB on my client side HTML file like this:

$('#btnSendMessage').click(function () {
       var msg = $("#txtMessage").val();

       if (msg.length > 0) {

           var userName = $('#hUserName').val();
           // <<<<<-- ***** Return to Server [  SaveMessagetoDB  ] *****
           objHub.server.saveMessagetoDB(userName, msg);

推荐答案

如果您决定将聊天存储在数据库中,则需要在消息发生时插入/更新消息.

If you decide to store the chats in a database, then you will need to insert/update the messages as they happen.

如果使用的是PersistentConnection,则可以插入OnReceivedAsync事件并从该事件插入/更新数据:

If you are using the PersistentConnection then you can hook into the OnReceivedAsync event and insert / update data from that event:

protected override Task OnConnectedAsync(IRequest request, string connectionId)
{
    _clients.Add(connectionId, string.Empty);
    ChatData chatData = new ChatData("Server", "A new user has joined the room.");
    return Connection.Broadcast(chatData);
}

或者在从Hub继承的SignalR类中,您可以在通知任何客户端之前一直保留到Db.

Or in the SignalR class that inherits from Hub, you can persist to the Db right before you have notified any clients.

这篇关于使用signalR在SQL数据库中存储聊天对话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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