如何在SignalR中正确安排我的ChatHub消息?

时间:2016-02-05 07:28:43

标签: javascript jquery asp.net-mvc signalr

到目前为止我使用了这段代码,但是我没有收到正确排序的消息输出,所以任何人都可以帮我正确输出。

ChatHub代码:

public class ChatHub : Hub
{
    static List<UserDetails> ConnectedUsers = new List<UserDetails>();
    static List<MessageDetails> CurrentMessage = new List<MessageDetails>();

    static List<TestProject1.Models.MessageDetails> CurrentMessage1 = new List<TestProject1.Models.MessageDetails>();

    private TestContext db = new TestContext();

    public void Connect(string userName)
    {
        var id = Context.ConnectionId;
        var data = db.MessageDetails.ToList();
        foreach (var item in data)
        {

            ConnectedUsers.Add(new UserDetails { ConnectionId = id, UserName = item.UserName });

            CurrentMessage1.Add(new TestProject1.Models.MessageDetails { UserName = item.UserName, Message = item.Message });
        }
        Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage1);

        Clients.AllExcept(id).onNewUserConnected(id, userName); 
    }

    public void Send(string name, string message, string connection)
    {
        AddMessageinCache(name, message);
        db.MessageDetails.Add(new TestProject1.Models.MessageDetails { UserName = name, Message = message });
        db.SaveChanges();
        Clients.All.addNewMessageToPage(name, message, connection);
    }

    private void AddMessageinCache(string userName, string message)
    {   
        CurrentMessage.Add(new MessageDetails { UserName = userName, Message = message });

        if (CurrentMessage.Count > 100)
            CurrentMessage.RemoveAt(0);
    }
}

我还在这里包含了我的HTML代码和CSHTML代码的详细信息:

<div id="page-content">
    <div id='wrap'>
        <div id="page-heading">
            <ol class="breadcrumb">
                <li><a href="@Url.Action("Index")">Dashboard</a></li>
                <li>Chat Room</li>
            </ol>    
            <h1>Chat Room</h1>    
        </div>    
        <div class="container">
            <div class="col-md-12">
                <div class="panel panel-inverse">
                    <div class="panel-heading">
                        <h4>Chat Room</h4>
                        <div class="options">
                            <a href="javascript:;"><i class="fa fa-cog"></i></a>
                            <a href="javascript:;"><i class="fa fa-refresh"></i></a>
                        </div>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="panel-chat well" id="chat">                                      
                                </div>
                                <form class="form-inline" action="#">
                                    <div class="input-group">
                                        <input type="text" placeholder="Enter your message here" id="message" class="form-control">
                                        <span class="input-group-btn">
                                            <button type="button" id="sendmessage" class="btn btn-primary"><i class="fa fa-comments-o"></i></button>
                                        </span>
                                    </div>
                                </form>
                                <input type="hidden" id="displayname" />
                                <input type="hidden" id="connection" />
                            </div>
                         </div>    
                    </div>
                </div>
            </div>
        </div>    
     </div> <!--wrap -->
</div> <!-- page-content -->       

@section Scripts
{
@Scripts.Render("~/bundles/jquery")
<script>
    jQuery(function () {
        $.connection.hub.url = 'http://localhost:34063//signalr';
        // Reference the auto-generated proxy for the hub.

        var chat = $.connection.chatHub;

        chat.client.onConnected = function (id, userName, allUsers, messages) {
            for (i = 0; i < messages.length; i++) {
                AddMessage(messages[i].UserName, messages[i].Message);
            }
        }

        // Create a function that the hub can call back to display messages.
        chat.client.addNewMessageToPage = function (name, message, connectionid) {
            // Add the message to the page.
            $('#chat').append('<div class="chat-message me"><div class="chat-contact"><img src="/Content/assets/demo/avatar/avatar.png" alt=""></div><div class="chat-text">' + htmlEncode(name)
                + ': ' + htmlEncode(message) + '</div></div>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val('@Session["User"].ToString()');
        $('#connection').val(@Session["UserID"]);
        var name = $('#displayname').val();

        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        var i = 0;
        $.connection.hub.start().done(function () {
            if (name.length > 0) {
                if (i == 1) {
                    chat.server.connect(name);
                }
            }

            $('#sendmessage').click(function () {
                chat.server.send($('#displayname').val(), $('#message').val(), $('#connection').val());
                $('#message').val('').focus();
            });
        });

        i = i + 1;
        $.connection.hub.disconnected(function () {
            alert('Disconnected');
        });
    });   

    // This optional function html-encodes messages for display in the page.
    function AddMessage(userName, message) {
        $('#chat').append('<div class="chat-message me"><div class="chat-contact"><img src="/Content/assets/demo/avatar/avatar.png" alt=""></div><div class="chat-text">' + userName + ': ' + message + '</div></div>');
    }

    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }
</script>
}

输出显示所有消息,但未按排序顺序显示,并在加载页面时重复消息。我也想删除它。

1 个答案:

答案 0 :(得分:0)

为什么不在邮件中添加Instant instantWhenDue = Instant.now().minusSeconds( 1 ); 戳记。在// do some stuff… if ( Instant.now().isAfter( instantWhenDue ) ) { // do your extra work like say Hello… // Set when due to run again. instantWhenDue = Instant.now().plusMinutes( 30 ); } // do other stuff… 课程中添加一个属性:

DateTime

修改在接收消息时运行的代码:

MessageDetails

在客户端,您需要对public DateTime ReceivedOn{get;set;} 属性

上的消息进行排序
private void AddMessageinCache(string userName, string message)
{   
    CurrentMessage.Add(new MessageDetails { UserName = userName, Message = message, ReceivedOn=DateTime.Now });

    if (CurrentMessage.Count > 100)
        CurrentMessage.RemoveAt(0);
}

请参阅ReceivedOn中关于排序的this问题。

编辑: - 旁注,如果只有已收到的邮件有问题,那么为什么不提取从数据库本身排序的邮件?