ebook img

SignalR on .NET 6 - the Complete Guide: The easiest way to enable real-time two-way HTTP communication on .NET 6 PDF

166 Pages·2022·10.254 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview SignalR on .NET 6 - the Complete Guide: The easiest way to enable real-time two-way HTTP communication on .NET 6

SignalR on .NET 6 - the Complete Guide The easiest way to enable real-time two-way HTTP communication on .NET 6 Fiodar Sazanavets Thisbookisforsaleathttp://leanpub.com/signalronnet6-thecompleteguide Thisversionwaspublishedon2022-05-15 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce youdo. ©2021-2022FiodarSazanavets Tweet This Book! PleasehelpFiodarSazanavetsbyspreadingthewordaboutthisbookonTwitter! Thesuggestedtweetforthisbookis: HereisthecompleteguideonusingSignalRon.NET6! Thesuggestedhashtagforthisbookis#signalr. Findoutwhatotherpeoplearesayingaboutthebookbyclickingonthislinktosearchforthis hashtagonTwitter: #signalr Contents 1-IntroductiontoSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 WhatmakesSignalRsogreat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 ExampleusecasesforSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Whoisthisbookfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Thescopeofthisbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Howtousethisbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Bookstructure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Abouttheauthor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Gettingtouchwiththeauthor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2-Settingupyourproject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Settingupyourenvironment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 SettingupSignalRhub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 MakingSignalRhubstrongly-typed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3-In-browserSignalRclients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 SettingupJavaScriptclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 SettingupBlazorWebAssemblyclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 4-ExternalSignalRclients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Settingup.NETclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 SettingupJavaclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 SettinguparawWebSocketclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 CONTENTS Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 5-Sendingmessagestoindividualclientsorgroupsofclients . . . . . . . . . . . . . . . . . . 50 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Broadcastingmessagestoallclients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Sendingmessagestospecificclients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Workingwithclientgroups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 6-StreaminginSignalR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Whatisstreamingusedfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 ClientstreaminginSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 ServerstreaminginSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 7-AdvancedSignalRconfiguration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 ConfiguringSignalRserver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 ConfiguringSignalRclient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 ProsandconsofMessagePackprotocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 8-SecuringyourSignalRapplications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 WhatisCORSandwhyit’simportant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Settingupsinglesign-onprovider. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 ApplyingauthenticationinSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 ApplyingauthorizationinSignalR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 9-ScalingoutSignalRapplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 SettingupRedisbackplane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 RunningmultiplehubinstancesviaRedisbackplane . . . . . . . . . . . . . . . . . . . . . . . 140 CONTENTS UsingHubContexttosendmessagesfromoutsideSignalRhub . . . . . . . . . . . . . . . . . 144 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 10-IntroducingAzureSignalRService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 SettingupAzureSignalRService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 AddingAzureSignalRServicedependenciestoyourapplication . . . . . . . . . . . . . . . . 150 OverviewofAzureSignalRServiceRESTAPI . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Testyourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Furtherreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Wrappingup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Answerstoself-assessmentquestions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Chapter7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Chapter8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Chapter9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Chapter10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 1 - Introduction to SignalR Ifyouareasoftwaredeveloperwhobuildsweb,mobileorinternetofthings(IoT)applications,you will appreciate how important it is for your applications to have the ability to communicate with the server asynchronously and in real time. Also, you probably realize that the standard request- response model of communication isn’t fully suitable for modern apps. Sometimes, your client application(whetherit’sawebpage,amobileapporaserviceonanIoTdevice)needstobeableto receiveareal-timeupdatefromtheserverthatwasactuallytriggeredbyaneventontheserverand notbyaclientrequest. Weseethisfunctionalityeverywhere.Whenyouuseamessengerapp,youwouldexpecttoreceive a message as soon as someone has sent you one. When you control your IoT devices, you expect themtorespondtoyourcommandsassoonasyoutriggerthem. Buttheproblemwithsuchfunctionalityisthatthesaidfunctionalityisnotalwayseasytoimplement. Youcouldstillusetheclassicrequest-responsemodelandjustcarryonsendingrequeststotheserver untilyoureceivearighttypeofresponse.Butthiswouldbewasteful.And,ifyourclientapplication haslimitedbandwidthtoworkwith,youmaynotevenbeabletodoitatall,ascontinuousrequests to the server may end up using up the entire bandwidth really quickly. As well as all of this, your codetoimplementsuchabehaviorwouldprobablybewaymorecomplicatedthanitshouldbe. There is also an alternative - WebSocket protocol. This is a much better solution. The protocol was specifically designed to enable two-way communication between the client and the server. All you have to do is establish a connection between the two endpoints. And, as long as this connection is live,themessagescanflowbothways.Aswellassendinganyarbitrarymessagefromtheclientto theserver,youcanalsosendmessagesfromtheservertotheclient.And,ontopofthis,WebSocket protocolisveryefficient.Maintainingtheconnectiondoesn’tusemuchbandwidthatall. However,WebSocketdoesn’tcomewithoutitsownproblems.It’sfarfrombeingtheeasiestthingto workwith.Outofthebox,WebSocketprotocolusesrawdatainsteadofhuman-readableabstractions. Ittransmitsmessagesbyusingrawbytes.So,it’suptoyoutodoalltheassemblinganddisassembling of messages. It’s also up to you to monitor the state of the connection. The WebSocket code you’ll havetowritewillprobablylooksimilartothis,whichisneitherveryintuitivenoreasilyreadable: 1-IntroductiontoSignalR 2 Figure1.1-WebSocketimplementationexample Butifyouare.NETdeveloper,youwon’thavetodealwithanyofthis.Enablingefficientreal-time two-way communication will almost be as easy as making classes inside a single application call each other’s methods. And all of this was made possible with a help of a library called SignalR, whichisoneofthein-builtlibrariesof AS.NETCore. What makes SignalR so great SignalR is a library that is incredibly easy to implement compared to the alternatives. Using this library is just as easy as writing remote procedure calls. You will have some endpoint methods on your server that are just bog-standard C# methods. And, as long as you specify the methods of the same names on the client and put the expected parameters into them, the connection will be made andthemethodwillbetriggered. Same applies the other way round. Yourclient will haveeventlisteners with arbitrary names. And, as long as you spell the name of the listener correctly in your server-side code and apply expected datatypesasparameters,thelistenerontheclientwillbetriggered. Forexample,yourserver-sidemethodmaylooklikethis: 1-IntroductiontoSignalR 3 Figure1.2-Server-sideSignalRmethod Andyourclientcodethatwilltriggerthismethodmaylooklikethis: Figure1.3-Client-sideSignalRmethodinvocation Under the hood, SignalR library uses WebSocket protocol. But you, as a developer, don’t have to worry about implementation details of it. Those are abstracted away to make things as convenient foryouaspossible. But WebSocket is not the only protocol that SignalR uses, even though it is the default protocol it will try to use. It just happens that, although there aren’t many use cases where you won’t be able touseWebSocket,occasionallyyoumayencountersuchasituation.AndthisiswhySignalRcomes with two fallback protocols, which are server-sent events and long polling. The fallback order is as follows: 1. Ifpossible,useWebSocket 2. IfWebSocketcan’tbeused,useserver-sentevents 3. Ifserver-senteventscan’tbeused,uselongpolling Longpollingistheleastefficientprotocolofthemall.ThisiswheretheclientsendsastandardHTTP request to the server and just waits until the response is sent back. This is why you won’t be using thisprotocoluntilabsolutelynecessary.Butthemainbenefitofitisthatabsolutelyanysystemthat supportsHTTPsupportslongpolling. If you need to, you can even explicitly specify the protocol in the client configuration. But in most cases,youwon’thaveto.Butevenifyoudo,thechoiceoftheprotocolwillhavezeroimpactonthe wayyouwriteyourcode.Allyourcodewillbeidenticalregardlessoftheprotocolbeingused. Example use cases for SignalR SignalRisaperfectlibrarytobeusedinanyscenarioswhereclientsneedtoreceivereal-timeupdates fromtheserverorthereishighahighfrequencyofdataexchangebetweentheclientandtheserver. Aspertheofficialdocumentation¹,thefollowingaresomeoftheexampleswhereSignalRisanideal librarytouse: ¹https://docs.microsoft.com/en-us/azure/azure-signalr/signalr-overview 1-IntroductiontoSignalR 4 • Highfrequencydataupdates:gaming,voting,polling,auction. • Dashboardsandmonitoring:companydashboard,financialmarketdata,instantsalesupdate, multi-playergameleaderboard,andIoTmonitoring. • Chat:livechatroom,chatbot,on-linecustomersupport,real-timeshoppingassistant,messen- ger,in-gamechat,andsoon. • Real-time location on map: logistic tracking, delivery status tracking, transportation status updates,GPSapps. • Realtimetargetedads:personalizedrealtimepushadsandoffers,interactiveads. • Collaborativeapps:coauthoring,whiteboardappsandteammeetingsoftware. • Pushnotifications:socialnetwork,email,game,travelalert. • Real-time broadcasting: live audio/video broadcasting, live captioning, translating, events/newsbroadcasting. • IoT and connected devices: real-time IoT metrics, remote control, real-time status, and locationtracking. • Automation:real-timetriggerfromupstreamevents. Who is this book for This book will be useful to any ASP.NET Core developer who is interested in enabling real-time two-way communication between the clients and the server. Whether you are building a real-time chatapplication,amessengerapp,oranIoTcontrolhub,youwillfindtheinformationinthisbook useful. The scope of this book ThisbookwillteachyoueverythingyouwillneedtoknowaboutSignalR,soyouwillbeabletouse itinanytypeofprojectwhereitcanprovidebenefits.Wewon’tgotoodeepintotheinnerworkings of the library, but we will cover enough so you know how to use it in the most optimal way. We willevencoversomeusecasesthataren’tofficiallydocumented,butthatmayactuallyhappen.For example,youwilllearnhowtoconnectarawWebSocketclienttotheSignalRserverhub.Thisisa usecaseIhavepersonallydealtwithinoneofmyprojects. Another topic that we will address is how to integrate the latest .NET 6 and C# 10 features with SignalR.ThereisawealthofinformationonlineonhowtouseSignalR,butsince.NET6isrelatively recent, there isn’t much information on how to take advantage of the latest .NET 6 features while usingit.Andthisbookisaimingtoaddressthisgap. In this book, you will be working on the same .NET solution throughout the chapters, adding new features to it as you go along. All the code samples used in the book are available in this GitHub repo: https://github.com/fiodarsazanavets/SignalR-on-.NET-6---the-complete-guide

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.