Einstieg in SignalR 2.0 & Azure Website Websockets

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • <p>SignalR ist ein Open Source Framework für Real Time WebApps. Das größte Problem am Real-Time im Web ist der Kanal zwischen Browser und Server. Wer noch nie was mit SignalR und den Problemstellungen zu tun hatte, hier ein paar Eckpunkte:</p>


    Das Problem
    <p>Traditionell initiert der Browser den Request zum Server und der Server schickt eine Antwort. Wenn jetzt allerdings der Server Daten zum Browser schicken möchte sind die Möglichkeiten eingeschränkt.</p>


    Die “Problemlösungen”
    <p>Die älteste Variante ist über “<a href="http://code-inside.de/blog/2009/10/21/howtocode-reverse-ajax-http-push-comet-kann-der-server-clients-aktiv-infomieren/">Comet</a>”, darunter versteht man eine Ansammlung von Tricks. So wird zum Beispiel ein Request vom Client initiiert und erst geschlossen falls der Server Daten sendet. Grundsätzlich bleibt die Verbindung hier “ständig” offen. Diese Variante ist aber nicht wirklich elegant.</p>


    <p>Moderner geht es über so genannte “<a href="http://en.wikipedia.org/wiki/Server-sent_events">Server Sent Events</a>”, welche von fast allen Browsern unterstützt werden – außer dem IE. Ältere IEs müssen auf die alte Variante zurückgreifen. </p>


    <p>Die “modernste” Variante sind so genannte WebSockets. Hierbei eine TCP Connection zwischen Server und Client aufgebaut und eine bidirektionale wird aufgebaut.</p>


    Das “Problem” bei WebSockets
    <p>WebSockets müssen nicht nur im Browser unterstützt werden, sondern auch vom Server. Im IIS selbst sind Websockets erst ab IIS 8.0 offiziell unterstützt. Das heisst nur ab Windows Server 2012. Davor gibt es in der IIS Pipeline keinen Weg das zu aktivieren.</p>


    <p>Auf Browser Seite gibt es die Websockets-Unterstützt seit IE 10. Chome und Firefox unterstüten Websockets schon länger und alle modernen Browser haben das Feature implementiert.</p>


    SignalR – Real Time für alle
    <p>Da es verschiedene “Protokoll-Arten” gibt und die Unterstützung sowohl vom Client als auch Server abhängig ist, ist es nicht ganz trivial Apps zu bauen. Hier kommt nun SignalR zum Zuge. SignalR baut automatisch die “best-mögliche” Verbindung auf und zudem bringt es ein sehr beeindruckendes Programmiermodell mit. SignalR selbst ist Open Source und der Code steht auf GitHub bereit. Trotzdem bekommt man (wenn man darauf angewiesen ist) vollen Support von Microsoft.</p>


    SignalR DemoHub
    <p>Das Beispiel stammt aus <a href="https://github.com/SignalR/Samples/tree/master/Samples_2.1.0/WebApplication/Features/Hub">dem GitHub Account</a>:</p>




    1: public class DemoHub : Hub
    <p>
    2: {
    <p>
    3: public override Task OnConnected()
    <p>
    4: {
    <p>
    5: return Clients.All.hubMessage("OnConnected " + Context.ConnectionId);
    <p>
    6: }
    <p>
    7:&nbsp;
    <p>
    8: public override Task OnDisconnected()
    <p>
    9: {
    <p>
    10: return Clients.All.hubMessage("OnDisconnected " + Context.ConnectionId);
    <p>
    11: }
    <p>
    12:&nbsp;
    <p>
    13: public override Task OnReconnected()
    <p>
    14: {
    <p>
    15: return Clients.Caller.hubMessage("OnReconnected");
    <p>
    16: }
    <p>
    17:&nbsp;
    <p>
    18: public void SendToMe(string value)
    <p>
    19: {
    <p>
    20: Clients.Caller.hubMessage(value);
    <p>
    21: }
    <p>
    22:&nbsp;
    <p>
    23: public void SendToConnectionId(string connectionId, string value)
    <p>
    24: {
    <p>
    25: Clients.Client(connectionId).hubMessage(value);
    <p>
    26: }
    <p>
    27:&nbsp;
    <p>
    28: public void SendToAll(string value)
    <p>
    29: {
    <p>
    30: Clients.All.hubMessage(value);
    <p>
    31: }
    <p>
    32:&nbsp;
    <p>
    33: public void SendToGroup(string groupName, string value)
    <p>
    34: {
    <p>
    35: Clients.Group(groupName).hubMessage(value);
    <p>
    36: }
    <p>
    37:&nbsp;
    <p>
    38: public void JoinGroup(string groupName, string connectionId)
    <p>
    39: {
    <p>
    40: if (string.IsNullOrEmpty(connectionId))
    <p>
    41: {
    <p>
    42: connectionId = Context.ConnectionId;
    <p>
    43: }
    <p>
    44:
    <p>
    45: Groups.Add(connectionId, groupName);
    <p>
    46: Clients.All.hubMessage(connectionId + " joined group " + groupName);
    <p>
    47: }
    <p>
    48:&nbsp;
    <p>
    49: public void LeaveGroup(string groupName, string connectionId)
    <p>
    50: {
    <p>
    51: if (string.IsNullOrEmpty(connectionId))
    <p>
    52: {
    <p>
    53: connectionId = Context.ConnectionId;
    <p>
    54: }
    <p>
    55:
    <p>
    56: Groups.Remove(connectionId, groupName);
    <p>
    57: Clients.All.hubMessage(connectionId + " left group " + groupName);
    <p>
    58: }
    <p>
    59:&nbsp;
    <p>
    60: public void IncrementClientVariable()
    <p>
    61: {
    <p>
    62: Clients.Caller.counter = Clients.Caller.counter + 1;
    <p>
    63: Clients.Caller.hubMessage("Incremented counter to " + Clients.Caller.counter);
    <p>
    64: }
    <p>
    65:&nbsp;
    <p>
    66: public void ThrowOnVoidMethod()
    <p>
    67: {
    <p>
    68: throw new InvalidOperationException("ThrowOnVoidMethod");
    <p>
    69: }
    <p>
    70:&nbsp;
    <p>
    71: public async Task ThrowOnTaskMethod()
    <p>
    72: {
    <p>
    73: await Task.Delay(TimeSpan.FromSeconds(1));
    <p>
    74: throw new InvalidOperationException("ThrowOnTaskMethod");
    <p>
    75: }
    <p>
    76:&nbsp;
    <p>
    77: public void ThrowHubException()
    <p>
    78: {
    <p>
    79: throw new HubException("ThrowHubException", new { Detail = "I can provide additional error information here!" });
    <p>
    80: }
    <p>
    81:&nbsp;
    <p>
    82: public void StartBackgroundThread()
    <p>
    83: {
    <p>
    84: BackgroundThread.Enabled = true;
    <p>
    85: BackgroundThread.SendOnPersistentConnection();
    <p>
    86: BackgroundThread.SendOnHub();
    <p>
    87: }
    <p>
    88:&nbsp;
    <p>
    89: public void StopBackgroundThread()
    <p>
    90: {
    <p>
    91: BackgroundThread.Enabled = false;
    <p>
    92: }
    <p>
    93: }
    <p>

    <p>Server-Seitig wird ein Hub definiert und per API kann man “Client-Funktionen” aufrufen – so z.B. “hubMessage”.</p>


    <p>Diese Methode sind im Javascript definiert und SignalR sort für dessen Aufruf:</p>




    1: function writeError(line) {
    <p>
    2: var messages = $("#messages");
    <p>
    3: messages.append("&lt;li style='color:red;'&gt;" + getTimeString() + ' ' + line + "&lt;/li&gt;");
    <p>
    4: }
    <p>
    5:&nbsp;
    <p>
    6: function writeEvent(line) {
    <p>
    7: var messages = $("#messages");
    <p>
    8: messages.append("&lt;li style='color:blue;'&gt;" + getTimeString() + ' ' + line + "&lt;/li&gt;");
    <p>
    9: }
    <p>
    10:&nbsp;
    <p>
    11: function writeLine(line) {
    <p>
    12: var messages = $("#messages");
    <p>
    13: messages.append("&lt;li style='color:black;'&gt;" + getTimeString() + ' ' + line + "&lt;/li&gt;");
    <p>
    14: }
    <p>
    15:&nbsp;
    <p>
    16: function getTimeString() {
    <p>
    17: var currentTime = new Date();
    <p>
    18: return currentTime.toTimeString();
    <p>
    19: }
    <p>
    20:&nbsp;
    <p>
    21: function printState(state) {
    <p>
    22: var messages = $("#Messages");
    <p>
    23: return ["connecting", "connected", "reconnecting", state, "disconnected"][state];
    <p>
    24: }
    <p>
    25:&nbsp;
    <p>
    26: function getQueryVariable(variable) {
    <p>
    27: var query = window.location.search.substring(1),
    <p>
    28: vars = query.split("&amp;"),
    <p>
    29: pair;
    <p>
    30: for (var i = 0; i &lt; vars.length; i++) {
    <p>
    31: pair = vars[i].split("=");
    <p>
    32: if (pair[0] == variable) {
    <p>
    33: return unescape(pair[1]);
    <p>
    34: }
    <p>
    35: }
    <p>
    36: }
    <p>
    37:&nbsp;
    <p>
    38: $(function () {
    <p>
    39: var connection = $.connection.hub,
    <p>
    40: hub = $.connection.demoHub;
    <p>
    41:&nbsp;
    <p>
    42: connection.logging = true;
    <p>
    43:&nbsp;
    <p>
    44: connection.connectionSlow(function () {
    <p>
    45: writeEvent("connectionSlow");
    <p>
    46: });
    <p>
    47:&nbsp;
    <p>
    48: connection.disconnected(function () {
    <p>
    49: writeEvent("disconnected");
    <p>
    50: });
    <p>
    51:&nbsp;
    <p>
    52: connection.error(function (error) {
    <p>
    53: writeError(error);
    <p>
    54: });
    <p>
    55:&nbsp;
    <p>
    56: connection.reconnected(function () {
    <p>
    57: writeEvent("reconnected");
    <p>
    58: });
    <p>
    59:&nbsp;
    <p>
    60: connection.reconnecting(function () {
    <p>
    61: writeEvent("reconnecting");
    <p>
    62: });
    <p>
    63:&nbsp;
    <p>
    64: connection.starting(function () {
    <p>
    65: writeEvent("starting");
    <p>
    66: });
    <p>
    67:&nbsp;
    <p>
    68: connection.stateChanged(function (state) {
    <p>
    69: writeEvent("stateChanged " + printState(state.oldState) + " =&gt; " + printState(state.newState));
    <p>
    70: var buttonIcon = $("#startStopIcon");
    <p>
    71: var buttonText = $("#startStopText");
    <p>
    72: if (printState(state.newState) == "connected") {
    <p>
    73: buttonIcon.removeClass("glyphicon glyphicon-play");
    <p>
    74: buttonIcon.addClass("glyphicon glyphicon-stop");
    <p>
    75: buttonText.text("Stop Connection");
    <p>
    76: } else if (printState(state.newState) == "disconnected") {
    <p>
    77: buttonIcon.removeClass("glyphicon glyphicon-stop");
    <p>
    78: buttonIcon.addClass("glyphicon glyphicon-play");
    <p>
    79: buttonText.text("Start Connection");
    <p>
    80: }
    <p>
    81: });
    <p>
    82:&nbsp;
    <p>
    83: hub.client.hubMessage = function (data) {
    <p>
    84: writeLine("hubMessage: " + data);
    <p>
    85: }
    <p>
    86:&nbsp;
    <p>
    87: $("#startStop").click(function () {
    <p>
    88: if (printState(connection.state) == "connected") {
    <p>
    89: connection.stop();
    <p>
    90: } else if (printState(connection.state) == "disconnected") {
    <p>
    91: var activeTransport = getQueryVariable("transport") || "auto";
    <p>
    92: connection.start({ transport: activeTransport })
    <p>
    93: .done(function () {
    <p>
    94: writeLine("connection started. Id=" + connection.id + ". Transport=" + connection.transport.name);
    <p>
    95: })
    <p>
    96: .fail(function (error) {
    <p>
    97: writeError(error);
    <p>
    98: });
    <p>
    99: }
    <p>
    100: });
    <p>
    101:&nbsp;
    <p>
    102: $("#sendToMe").click(function () {
    <p>
    103: hub.server.sendToMe($("#message").val());
    <p>
    104: });
    <p>
    105:&nbsp;
    <p>
    106: $("#sendToConnectionId").click(function () {
    <p>
    107: hub.server.sendToConnectionId($("#connectionId").val(), $("#message").val());
    <p>
    108: });
    <p>
    109:&nbsp;
    <p>
    110: $("#sendBroadcast").click(function () {
    <p>
    111: hub.server.sendToAll($("#message").val());
    <p>
    112: });
    <p>
    113:&nbsp;
    <p>
    114: $("#sendToGroup").click(function () {
    <p>
    115: hub.server.sendToGroup($("#groupName").val(), $("#message").val());
    <p>
    116: });
    <p>
    117:&nbsp;
    <p>
    118: $("#joinGroup").click(function () {
    <p>
    119: hub.server.joinGroup($("#groupName").val(), $("#connectionId").val());
    <p>
    120: });
    <p>
    121:&nbsp;
    <p>
    122: $("#leaveGroup").click(function () {
    <p>
    123: hub.server.leaveGroup($("#groupName").val(), $("#connectionId").val());
    <p>
    124: });
    <p>
    125:&nbsp;
    <p>
    126: $("#clientVariable").click(function () {
    <p>
    127: if (!hub.state.counter) {
    <p>
    128: hub.state.counter = 0;
    <p>
    129: }
    <p>
    130: hub.server.incrementClientVariable();
    <p>
    131: });
    <p>
    132:&nbsp;
    <p>
    133: $("#throwOnVoidMethod").click(function () {
    <p>
    134: hub.server.throwOnVoidMethod()
    <p>
    135: .done(function (value) {
    <p>
    136: writeLine(result);
    <p>
    137: })
    <p>
    138: .fail(function (error) {
    <p>
    139: writeError(error);
    <p>
    140: });
    <p>
    141: });
    <p>
    142:&nbsp;
    <p>
    143: $("#throwOnTaskMethod").click(function () {
    <p>
    144: hub.server.throwOnTaskMethod()
    <p>
    145: .done(function (value) {
    <p>
    146: writeLine(result);
    <p>
    147: })
    <p>
    148: .fail(function (error) {
    <p>
    149: writeError(error);
    <p>
    150: });
    <p>
    151: });
    <p>
    152:&nbsp;
    <p>
    153: $("#throwHubException").click(function () {
    <p>
    154: hub.server.throwHubException()
    <p>
    155: .done(function (value) {
    <p>
    156: writeLine(result);
    <p>
    157: })
    <p>
    158: .fail(function (error) {
    <p>
    159: writeError(error.message + "&lt;pre&gt;" + connection.json.stringify(error.data) + "&lt;/pre&gt;");
    <p>
    160: });
    <p>
    161: });
    <p>
    162: });
    <p>

    Was ist neu in SignalR 2.0?
    <p>Damian Edwards hat auf <a href="https://github.com/DamianEdwards/SignalR-2.x-demo">seinem GitHub Account ein kleines Demoprojekt</a> angelegt:</p>


    <p><a href="https://github.com/DamianEdwards/SignalR-2.x-demo"></a></p>


    Azure Websites &amp; Websockets
    <p>Seit gut einem Monat gibt es die <a href="http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx">Websockets Unterstütztung in Azure Websites</a>. Im Standardfall ist die Websocketsunterstützung deaktiviert. Die Einstellung kann man direkt im Azure Managementportal machen:</p>


    <p><a href="http://code-inside.de/blog/wp-content/uploads/image1964.png"></a></p>


    <p> Wenn man da die SignalR Demoanwendung laufen lässt (ohne Websockets Support) sieht der Traffic so aus:</p>


    <p><a href="http://code-inside.de/blog/wp-content/uploads/image1965.png"></a></p>


    <p>Mit Websocket Support:</p>


    <p><a href="http://code-inside.de/blog/wp-content/uploads/image1966.png"></a></p>


    <p>Das tollen an SignalR: Der “Transportweg” ist erst einmal egal. Diese Sache übernimmt SignalR und man kann sich selbst auf die eigentliche Funktionalität konzentrieren.</p>


    SignalR Ressourcen
    <p>Wer sich weiter informieren möchte, hier einige Links die ich ganz interessant fand:</p>


    <p>- <a href="http://www.asp.net/signalr/overview/signalr-20">ASP.NET SignalR Tutorial</a><br />

    - <a href="https://jabbr.net/#/rooms/signalr">SignalR “JabbR” Raum</a> – Chat (gebaut mit SignalR) wo meist die Entwickler selbst anzutreffen sind.<br />

    - <a href="https://github.com/SignalR/">SignalR Account</a> auf GitHub</p>


    <p>Das <a href="http://vimeo.com/68383353">Video</a> von den beiden SignalR-“Hauptentwicklern”&nbsp; ist ziemlich beeindruckend:</p>


    <p>David Fowler, Damian Edwards: Under the covers with ASP.NET SignalR</p>


    <p>The real-time web is here. You’ve seen the demos before; synchronized moving shapes across browsers and Windows apps, but now you want to *really* understand what’s going on behind the curtain. What better way than to watch one of the SignalR co-creators build a SignalR-like framework from scratch on stage. Knowing how it works will help you use it better and might just prevent you making mistakes based on incorrect assumptions. Know your tools and learn the magic behind SignalR.</p>


    6.886 mal gelesen