利用signalr打造即時通訊@tech day geek

Post on 02-Jul-2015

1.644 Views

Category:

Internet

9 Downloads

Preview:

Click to see full reader

DESCRIPTION

SignalR是基於ASP.NET所發展的一項即時通訊技術, 幫你整合了各種通訊協定, 只要用一種統一的方式就可在網頁/APP/Windows form 間進行即時通訊, 符合目前資料在雲端, 應用程式在個平台上跑的目標

TRANSCRIPT

高榮章 2014-09-10

利用Signalr打造即時通訊

1

http://trufflepenne.blogspot.tw/

BLOG:

在這之前

談談SignalR

Live demo

升級到SignalR 2

Performance Tuning

擴充(Scaling out)

Agenda

2

[在這之前]

Socket WCF 雙向(Duplex)

即時通訊的寫法:

3

Web的運作

網頁基於Http的運作,發起者都是Client,差別在於需不需要Postback

一般 Ajax

Client Server

要求

回覆網頁

處理

要求

回覆網頁

要求

回覆網頁

處理

處理

Client Server

要求

回覆網頁

處理

要求

回覆網頁

要求

回覆網頁

處理

處理

4

如果要在Web上實作即時通訊:聊天室?

Pulling是好方法?

是很簡單

但代價太高

大部分時間是虛工

5

Html 5的Web socket帶來一道曙光

persistent connection

two-way channel

6

小明 Server

Connect

明天Tech day哪等?

市政府捷運站

大雄

明天Tech day哪等?

Connect

市政府捷運站

Process

Process

Process

Process

Connection

即時通訊仍有一些麻煩事

持續連線要自行處理

處理訂閱

斷線偵測

偵測狀態改變

訊息要自行解析

如果要進行網頁和Win form 互傳?

不支援WebSocket怎麼辦

7

[談談SignalR]

Client Hub

用戶 伺服器

Client

Connection

GroupMessage

8

SignalR架構

Hubs

Persistent connections

Transports

Internet Protocols

Forever frame Long pooling Server-Event Websoket

虛擬層級

9

程式概念

10

SignalR Push通訊類型

• Html 5Websoket

Server-Send Event

• CometLong poolingForever frame

11

Server-send Event

12

小明 Server

Connect

Event

Event

Process

Process

Process

Process

Connection

Event

Long Pulling

13

小明 Server

有新訊息?

明天Tech day坐捷運去

0900到

大雄

明天Tech day坐捷運去?

0900到

HTTP

有新訊息?

HTTP

Forever frame

14

小明 Server

GET/Forever

<script>addMsg(1,"

明天Tech day坐捷運去:);</script>

<script>addMsg(1,"

0900到:);</script>

大雄

明天Tech day坐捷運去?

0900到

HTTP

HTTP

HTTP

適用平台(1)

Browser

Windows Desktop

15

適用平台(2)

Windows Store App/Phone app

16

SignalR 2 快速上手

• 安裝.net 4.5

• 新增一個空白asp.net專案

• 套件管理器主控台install-package Microsoft.AspNet.SignalRInstall-Package json2 17

Hub(1)

• Host• IIS:ASP.NET

• Self: Windows Service with Owin

• 新增項目, 選SignalR Hub類別 (v2)

using System;using System.Web;using Microsoft.AspNet.SignalR;namespace SignalRChat{

public class ChatHub : Hub{

public void Send(string name, string message){

// Call the broadcastMessage method to update clients.Clients.All.broadcastMessage(name, message);

}}

}

18

Hub(2)

• 新增startup項目, 選OWIN 啟動類別

using Microsoft.Owin;using Owin;

[assembly: OwinStartup(typeof(SignalRChat.Startup))]namespace SignalRChat{

public class Startup{

public void Configuration(IAppBuilder app){

app.MapSignalR();}

}}

19

Client(1)

• 新增一個Html

20

<!DOCTYPE html><html><head>

<title>SignalR Simple Chat</title><style type="text/css">

.container {background-color: #99CCFF;border: thick solid #808080;padding: 20px;margin: 20px;

}</style>

</head><body>

<div class="container"><input type="text" id="message" /><input type="button" id="sendmessage" value="Send" /><input type="hidden" id="displayname" /><ul id="discussion"></ul>

</div><!--Script references. --><!--Reference the jQuery library. --><script src="Scripts/jquery-1.6.4.min.js" ></script><!--Reference the SignalR library. --><script src="Scripts/jquery.signalR-2.1.0.min.js"></script><!--Reference the autogenerated SignalR hub script. --><script src="signalr/hubs"></script>

Client(2)

21

<!--Add script to update the page and send messages.--> <script type="text/javascript">

$(function () {// Declare a proxy to reference the hub. var chat = $.connection.chatHub;// Create a function that the hub can call to broadcast messages.chat.client.broadcastMessage = function (name, message) {

// Html encode display name and message. var encodedName = $('<div />').text(name).html();var encodedMsg = $('<div />').text(message).html();// Add the message to the page. $('#discussion').append('<li><strong>' + encodedName

+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');};// Get the user name and store it to prepend to messages.$('#displayname').val(prompt('Enter your name:', ''));// Set initial focus to message input box. $('#message').focus();// Start the connection.$.connection.hub.start().done(function () {

$('#sendmessage').click(function () {// Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val());// Clear text box and reset focus for next comment. $('#message').val('').focus();

});});

});</script>

</body></html>

[Live demo]

22

[升級到SignalR 2](1)

• 2.0持續使用 OWIN

• Target設為4.5

• 套件管理器主控台移除1.1>Uninstall-Package Microsoft.AspNet.SignalR –RemoveDependencies安裝2.0>Install-Package Microsoft.AspNet.SignalR

• Client js lib改為2.1

<!--Reference the SignalR library. --> <script

src="Scripts/jquery.signalR-2.1.0.min.js"></script>

23

升級到SignalR 2(2)

• Global.ascx.cs移除RouteTable

• 新增Owin startup

protected void Application_Start(object sender, EventArgs e){RouteTable.Routes.MapHubs();}

24

升級到SignalR 2(3)

• Startup.cs填入以下code

• Hub.cs增加Usingusing Microsoft.AspNet.SignalR;

using Microsoft.Owin;using Owin;

[assembly: OwinStartup(typeof(SignalRChat.Startup))]namespace SignalRChat{

public class Startup{

public void Configuration(IAppBuilder app){

app.MapSignalR();}

}}

25

[Performance Tuning](1)

https://github.com/SignalR/SignalR/wiki/Performance

• IIS Configuration Max concurrent requests per applicationm: 預設5000提升到 100,000

cd %windir%\System32\inetsrv\

appcmd.exe set config /section:system.webserver/serverRuntime

/appConcurrentRequestLimit:100000

26

[Performance Tuning](2)

• ASP.NET ConfigurationXmaxConCurrentRequestPerCPU: default 5000, 可以提到20000

打開%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet.config(Framework64 for 64 bit processes)

<?xml version="1.0" encoding="UTF-8" ?><configuration>

<runtime><legacyUnhandledExceptionPolicy enabled="false" /><legacyImpersonationPolicy enabled="true"/><alwaysFlowImpersonationPolicy enabled="false"/><SymbolReadingPolicy enabled="1" /><shadowCopyVerifyByTimestamp enabled="true"/>

</runtime><startup useLegacyV2RuntimeActivationPolicy="true" /><system.web>

<applicationPool maxConcurrentRequestsPerCPU="20000" /></system.web>

</configuration>

Request Qeue Limit:可以提到250000打開%windir%\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

<processModel autoConfig="false" requestQueueLimit="250000" /> 27

[Performance Tuning](3)

• 減少訊息頻率• 減低訊息大小:使用JasonIgnore

using Newtonsoft.Json; using System; public class ShapeModel{[JsonProperty("l")]

public double Left { get; set; }[JsonProperty("t")]

public double Top { get; set; }// We don't want the client to get the "LastUpdatedBy" property

[JsonIgnore]public string LastUpdatedBy { get; set; }

}

28

[Performance Tuning](4)

• SignalR configuration setting

DefaultMessageBufferSize :1000, 如果訊息過大, 可調降該值, ex:500

public class Startup

{

public void Configuration(IAppBuilder app)

{

// Any connection or hub wire up and configuration should go here

GlobalHost.Configuration.DefaultMessageBufferSize = 500;

app.MapSignalR();

}

}

29

[Performance Tuning](5)

• 測試SignalR負載工具-Cran

https://github.com/SignalR/SignalR/tree/dev/src/Microsoft.AspNet.S

ignalR.Crank

• SignalR performance counter

管理Nuget套件, 搜尋 signalr.utils

30

[Performance Tuning](6)

路徑:專案路經/packages/Microsoft.AspNet.SignalR.Utils.<version>/tools安裝 > SignalR.exe ipc

反安裝 > SignalR.exe upc

Windows 計數器> perfmon

31

Fiddler

32

擴充(Scaling out)

• Sqlserver

• Redius

• Azure survice bus

http://www.asp.net/signalr/overview/signalr-20/performance-and-scaling/scaleout-in-signalr

33

Signal R 2教學資源

http://www.asp.net/signalr/overview/signalr-20

34

35

top related