文章出處

SignalR是微軟ASP.NET技術體系中的新成員。

 

www.asp.net網站上的SignalR專區有一篇SignalR的入門級教程《Tutorial: Server Broadcast with ASP.NET SignalR (C#)》,介紹了通過SignalR實現服務器端廣播的方法。文章中實現了簡單的股票信息實時推送,這是一個服務器-客戶端雙向實時通信的典型應用。然而我覺得這篇教程雖然簡單,但是作為入門的話代碼量(特別是無關代碼量)顯得太多了,當時我用此教程學習的時候不得不從幾頁代碼中上下翻找與SignalR的使用有關的關鍵點,體驗不是很好。于是我自己練習時,另外寫了一個簡化版的Hello world,現在放出來跟大家交流。

 

我的示例很簡單,就是服務器端定時發起更新客戶端頁面上的一個字符串消息。消息內容也沒有花頭,直接在幾個固定內容中輪換。

 

服務器端:

 

public class MessagesHub : Hub

{

    static MessagesHub()

    {

        StringPusher.Init();

    }

}

 

public static class StringPusher

{

    private static string[] _messages = { "這是從服務器推送的消息。""使用ASP.NET SignalR技術實現。""從此不再需要客戶端定時發送請求。""可實現雙向實時通信。" };

    private static System.Timers.Timer _timer = new System.Timers.Timer(3000);

    private static IHubConnectionContext _clients = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>().Clients;

    private static int _messageIndex = 0;

 

    public static void Init()

    {

        _timer.Elapsed += (sender, e) => Broadcast();

        _timer.Start();

    }

 

    public static void Broadcast()

    {

        _messageIndex = (_messageIndex + 1) % _messages.Length;

        _clients.All.showMessage(_messages[_messageIndex]);

    }

}

 

客戶端:

 

$(document).ready(function () {

    var messagesHub = $.connection.messagesHub;

 

    messagesHub.client.showMessage = function (msg) {

        $('#footer').text(msg);

    };

 

    $.connection.hub.start();

});


文章列表


不含病毒。www.avast.com
全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()