使用带有C#的signalR每秒向客户端发送消息

时间:2016-04-11 11:26:06

标签: c# asp.net signalr signalr-hub

我想向服务器发送某种计时器给所有连接的客户端。 我点击了按钮就能做到这一点。但我真正需要的是每秒自动发送这个计时器。

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Signalr Chat Messenger</title>
    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-1.0.0-rc1.js" type="text/javascript"></script>
    <script src="signalr/hubs" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">

    <script type="text/javascript">
        $(function () {

            var IWannaChat = $.connection.myChatHub;

            IWannaChat.client.addMessage = function (message) {
                $('#listMessages').append('<li>' + message  + '</li>');
            };

            IWannaChat.client.addTest = function (timer) {
                $('#lblTimer').text(timer);
            };

            $("#SendMessage").click(function () {
                IWannaChat.server.send($('#txtMessage').val());
            });

            $.connection.hub.start();

        });
    </script>

    <div>
        <input type="text" id="txtMessage" />
        <input type="button" id="SendMessage" value="broadcast" /><asp:Label ID="lblTimer" runat="server" Text="timer"></asp:Label>
&nbsp;<ul id="listMessages">
        </ul>
    </div>
    </form>
</body>
</html>

这是我的 HUB

using System;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading;

namespace SignalRChat
{
    [HubName("myChatHub")]
    public class LetsChat : Hub
    {
        DateTime dateTime2 = DateTime.Now;
        string dateTime1 = "11.04.2016 15:49:00";   




        public void send(string message)
        {
            //Thread.Sleep(1000);
            var diffInSeconds = (Convert.ToDateTime(dateTime1) - dateTime2).TotalSeconds;

            Clients.All.addMessage(message);
            Clients.All.addTest(diffInSeconds.ToString());
            //Clients.All.addTest(dateTime1.ToString());
        }


    }
}

0 个答案:

没有答案