步驟1: 透過Nuget 安裝SignalR
步驟2: 在startup.cs 加上設定
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
app.MapSignalR();
}
}
|
步驟3: 如果在MVC的架構下,建議增加Hubs資料夾,新增Signal的hub類別
public class TimeQuery : Hub
{
static string messageToSend = DateTime.Now.ToString();
Timer t = new Timer(3000); //每間隔3秒鐘
public void StartTimer()
{
//開始啟動Timmer
t.Elapsed +=
t_Elapsed;
t.Start();
}
private void t_Elapsed(object sender, ElapsedEventArgs e)
{
//呼叫server 端
Clients.All.addMessage("Date time : " + messageToSend);
messageToSend = DateTime.Now.ToString();
}
}
|
PS:
這裡的Timer
的引用using System.Timers;
_Layout.html 引用以下的javaScript
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
|
Angular呼叫SignalR
<div ng-controller="winformNotify" ng-model= " servFileModel">
時鐘<div id="messages"></div>
</div>
<script>
var app = angular.module("servFileModel", []);
app.controller("winformNotify", function ($scope) {
//呼叫server 端的hub的類別名稱 (不論類別名稱是大小寫,呼叫開頭一律小寫)
var timeQuery = $.connection.timeQuery;
timeQuery.client.addMessage = function (message) {
$('#messages').empty();
$('#messages').append( message );
};
$.connection.hub.start().done(function () {
timeQuery.server.startTimer();
});
});
</script>
|
參考文獻
沒有留言:
張貼留言