Utilizando el servicio de notificaciones push/websockets de Azure SignalR en un ejemplo con un juego en tiempo real multi-pantalla(varios dispositivos convertidos en una big-screen) arrastrando la pelota sobre las pantallas táctiles.
Soccer multi-screen with Azure SignalR Services
Using the push notifications service / websockets of Azure SignalR in an example with a multi-screen real-time game (several devices converted into a big-screen) dragging the ball on the touch screens.
1. October 4th, 5th & 6th 2018.NET Conf AR v2018
Futbol multi-screen
con Azure SignalR Service
Ing. Jose A. Fernandez
Tech Lead
@fernandezja
2. October 4th, 5th & 6th 2018.NET Conf AR v2018
Agenda
• SignalR
• Que es? Que versiones existen?
• Diferencias/Cambios
• Ping charla v2017 #NETConfAR
• Performance/Escalamiento
• Demo
• Azure SignalR Service
• Configuracion
• Conexiones
3. October 4th, 5th & 6th 2018.NET Conf AR v2018
SignalR. Que es? Repasando
• Apps en real-time increíblemente simple para .NET
• Provee una capa de abstracción sobre algunos de los transportes
• API Hubs para server-based push hacia web clients
• Clientes for JavaScript/Typescript, C#, C++, & Java
• Tipo de Conexiones…
• Forever Frames
• ServerSentEvent
• LongPolling
• Websockets
4. October 4th, 5th & 6th 2018.NET Conf AR v2018
SignalR a la carta
• Dos versiones
ASP.NET SignalR
ASP.NET Core SignalR
5. October 4th, 5th & 6th 2018.NET Conf AR v2018
ASP.NET SignalR / ASP.NET Core SignalR
ASP.NET SignalR ASP.NET Core SignalR
Server NuGet Package Microsoft.AspNet.SignalR Microsoft.AspNetCore.App (.NET Core)
Microsoft.AspNetCore.SignalR (.NET
Framework)
Client NuGet Packages Microsoft.AspNet.SignalR.Client
Microsoft.AspNet.SignalR.JS
Microsoft.AspNetCore.SignalR.Client
Client npm Package signalr @aspnet/signalr
Server App Type ASP.NET (System.Web) or OWIN Self-Host ASP.NET Core
Supported Server Platforms .NET Framework 4.5 or later .NET Framework 4.6.1 or later
.NET Core 2.1 or later
https://docs.microsoft.com/en-us/aspnet/core/signalr/version-differences?view=aspnetcore-2.1
6. October 4th, 5th & 6th 2018.NET Conf AR v2018
Ping to! Charla de v2017 #NETConfAR
• Aplicaciones en tiempo real con SignalR Core
https://youtu.be/EeAODcaeoqA
• Florencia Nodar
• Nicolas Granata
7. October 4th, 5th & 6th 2018.NET Conf AR v2018
Cambios
• Reconexiones automáticas.
• No se admiten
• Protocolos de mensajes
• JSON
• MessagePack (binario)
• … y se puede extender
• Streaming
8. October 4th, 5th & 6th 2018.NET Conf AR v2018
SignalR
¿Dónde se ejecuta?
9. October 4th, 5th & 6th 2018.NET Conf AR v2018
Donde se ejecuta?
• Para aplicaciones .NET…
• en nuestra apps,
• en el mismo contexto
• ¿Y si vamos a recibir miles de mensajes por segundo?
• Tenemos que escalar? Como?
• Garantizar que el rendimiento no se vea obstaculizado por la
generación de tráfico de red innecesario.
10. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalando
SignalR
mmm!
11. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalando SignalR
• Regulación de frecuencia de mensajes
• Cantidad de mensajes por segundo
• Pool de mensajes. Queue… y enviar en un rate adecuado
• Reducir el tamaño del mensaje
• Ver el objeto de transferencia (DTO).
• Propiedades… socialización
• Propiedades… nombres
• MessagePack!
12. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalando/Performance SignalR
• Regulación de frecuencia de mensajes
• Cantidad de mensajes por segundo
• Pool de mensajes. Queue… y enviar en un rate adecuado
• Reducir el tamaño del mensaje
• Ver el objeto de transferencia (DTO).
• Propiedades… socialización
• Propiedades… nombres
• MessagePack!
13. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalando/Performance SignalR
• Ajuste de su servidor SignalR …rendimiento
• DefaultMessageBufferSize
• Por Default … SignalR conserva 1000 mensajes en memoria por Hub por
conexión
• Mensajes grandes?
• Ajustes de configuración de IIS
• Max concurrent requests per application
• ApplicationPool QueueLength
cd %windir%System32inetsrv appcmd.exe set config
/section:system.webserver/serverRuntime
/appConcurrentRequestLimit:10000
14. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalando/Performance SignalR
• ASP.NET Configuracion de la Apps
• Maximum concurrent requests per CPU
• Request Queue Limit
<configuration>
<system.web>
<applicationPool maxConcurrentRequestsPerCPU="20000" />
</system.web>
</configuration>
<processModel autoConfig="false" requestQueueLimit="250000" />
15. October 4th, 5th & 6th 2018.NET Conf AR v2018
Scale out SignalR
https://docs.microsoft.com/en-us/aspnet/signalr/overview/performance/scaleout-in-signalr
+ Servers Con Backplane
16. October 4th, 5th & 6th 2018.NET Conf AR v2018
SignalR Backplanes
• Azure Service Bus
• Redis
• SQL Server
17. October 4th, 5th & 6th 2018.NET Conf AR v2018
Ops!
Operaciones
Infraestructura
18. October 4th, 5th & 6th 2018.NET Conf AR v2018
MessagePack en ASP.NET Core SignalR
• It's like JSON.
but fast and small.
• https://msgpack.org/
19. October 4th, 5th & 6th 2018.NET Conf AR v2018
Streaming en ASP.NET Core SignalR
• Admite la transmisión streaming desde el servidor
• Util….cuando los fragmentos de datos llegaran en un lapso de tiempo.
• Cada fragmento se envía al cliente tan pronto como está disponible
20. October 4th, 5th & 6th 2018.NET Conf AR v2018
Streaming
en ASP.NET
Core
SignalR
24. October 4th, 5th & 6th 2018.NET Conf AR v2018
Demo
http://bit.ly/soccer-signalr
25. October 4th, 5th & 6th 2018.NET Conf AR v2018
Azure SignalR Service
https://azure.com/signalr
26. October 4th, 5th & 6th 2018.NET Conf AR v2018
Azure SignalR Service
https://azure.com/signalr
• Es un servicio completamente administrado
• Permite utilizar ASP.NET Core SignalR para
crear app que requieran experiencias e
interacciones en tiempo real
• Como chat, live panels, gráficos, futbol...
• Sin preocuparse por
• el aprovisionamiento de la capacidad,
• el escalamiento
• o las conexiones persistentes.
29. October 4th, 5th & 6th 2018.NET Conf AR v2018
Azure SignalR Service…
Rápido
y Sencillo
Centrado en el
negocio
Potencial con
otros servicios
30. October 4th, 5th & 6th 2018.NET Conf AR v2018
Si ya utilizamos SignalR ….
• Paquete Microsoft.Azure.SignalR (Core)
...Microsoft.Azure.SignalR.AspNet
• Configuración Liviana (en Startup)
Rápido
y Sencillo
31. October 4th, 5th & 6th 2018.NET Conf AR v2018
Si ya utilizamos SignalR ….
• ConectionString
1. Environment Variable
• Azure:SignalR:ConnectionString
• Azure__SignalR__ConnectionString
2. Param en AddAzureSignalR(“…”)
Rápido
y Sencillo
32. October 4th, 5th & 6th 2018.NET Conf AR v2018
Cliente….
• Mismo cliente de ASP.NET SignalR Core
npm install @aspnet/signalr
<script src="/lib/signalr/signalr.js"></script>
33. October 4th, 5th & 6th 2018.NET Conf AR v2018
Cliente….
• Misma configuración
• No hay nada exclusivo
de Azure SignalR
35. October 4th, 5th & 6th 2018.NET Conf AR v2018
Conexiones del Servidor: Azure SignalR Service
• Expone endpoints por cada Hubs
• Responderá los request de conexiones
• Redirección al app service
• App server al iniciar el SDK abrirá
5 conexiones websockets
con el servicio de SignalR
• Siempre debe estar conectadas !!
• Si se desconecta, se cae todos los clientes
• Se auto reconecta
36. October 4th, 5th & 6th 2018.NET Conf AR v2018
Conexiones de Clientes: Azure SignalR Service
• Los clientes se conectan al Servicio
…en lugar del app server
• Proceso Cliente Request
1. Envía una solicitud de negociación
al app server
2. Con el SDK de Azure SignalR Service,
el app server devolverá una respuesta
de negociación de redireccionamiento
1. …con la URL del servicio de SignalR
y el token de acceso.
37. October 4th, 5th & 6th 2018.NET Conf AR v2018
Transporte de Datos: Azure SignalR Service
• Cliente se conectan al servicio
• Es valido hasta…
• El cliente se desconecte
• o el servidor de apps se desconecte
• Es una capa de transporte lógico
• Entre app server y clientes
• Todas las conexiones Azure SignalR
• El App Server lógica de Hubs
38. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalar Apps Services… A tener en cuenta
• Las conexiones van fuera del aplicación
• Pero la lógica de los Hubs todavía va a ser necesario escalar
• Cuando tendremos una carga significativa
39. October 4th, 5th & 6th 2018.NET Conf AR v2018
Escalar Apps Services…
• Varios app servers pueden conectarse a la misma instancia
del Azure SignalR.
• Mismo nombre de clase del Hub
• Se agrupan en el mismo Hub
• Cada conexión/cliente
• Se creara un uno solo app server
• Los mensajes del cliente se enviaran al mismo app server
• ¿Queremos acceder a Info del cliente globalmente?
• … Algun storage para read/write
41. October 4th, 5th & 6th 2018.NET Conf AR v2018
Azure SignalR Service
• Disponibilidad para utilizar con ASP.NET Core SignalR
• Todavía en public preview para ASP.NET SignalR
• Azure Functions binding
• https://github.com/Azure/azure-functions-signalrservice-extension
September 24, 2018
Azure SignalR Service now generally available
https://azure.microsoft.com/en-us/blog/azure-signalr-service-now-generally-available/
42. October 4th, 5th & 6th 2018.NET Conf AR v2018
Lista de Deseos… para la Demo.
• Soporte para recordar ID de pantalla en el browser
• Reconexión
• Mejorar la UI (Arcos, Gol)
• Mosaico mas amplio
• Extender ejemplo …
• Imágenes, Big-Screen
• #CosmosDB
• Serverless #AzureFunctions
• SaaS
44. October 4th, 5th & 6th 2018.NET Conf AR v2018
Enlaces
• https://azure.com/signalr
• https://docs.microsoft.com/en-us/azure/azure-signalr/
• https://github.com/fernandezja/soccer-multi-screen-
signalr/tree/master
45. October 4th, 5th & 6th 2018.NET Conf AR v2018
Muchas Gracias!
https://github.com/fernandezja
@fernandezja
Ing. Jose A. Fernandez
https://www.linkedin.com/in/fernandezja/
Notas del editor
API interfaces and behaviors are different
Con el servicio Azure SignalR, agregar comunicaciones en tiempo real a su aplicación web es tan simple como aprovisionar un servicio, ¡no es necesario que sea un gurú de las comunicaciones en tiempo real!
No tiene que aprovisionar y mantener servidores solo porque necesita funciones en tiempo real en su solución. El servicio SignalR se administra completamente, lo que facilita la adición de funciones de comunicación en tiempo real a su aplicación. ¡No se preocupe más por el alojamiento, la escalabilidad, el equilibrio de carga y tales detalles!
¡Benefíciese de todo lo que Azure tiene para ofrecer! Se integra fácilmente con servicios como Azure Functions, Azure Active Directory, Azure Storage, Azure App Service, Azure Analytics, Power BI, IoT, Servicios cognitivos, Machine Learning y más.
services.AddSignalR() .AddAzureSignalR(<replace with your connection string>);
or
services.AddSignalR() .AddAzureSignalR(options => options.ConnectionString = <replace with your connection string>);
ConnectionCount
Esta opción controla el número de conexiones entre el servidor de aplicaciones y el servicio Azure SignalR
AccessTokenLifetime
El valor predeterminado es 1 hora.
Esta opción controla la vida útil válida del token de acceso, que es generado por Service SDK para cada cliente. El token de acceso se devuelve en la respuesta a la solicitud de negociación del cliente.
Cuando se utiliza ServerSentEvent o LongPolling como transporte, la conexión del cliente se cerrará debido a un error de autenticación después del tiempo de caducidad. Puede aumentar este valor para evitar la desconexión del cliente.
ClaimsProvider
Esta opción controla los reclamos que desea asociar con la conexión del cliente. Se utilizará cuando Service SDK genere un token de acceso para el cliente en la solicitud de negociación del cliente. De forma predeterminada, todas las reclamaciones de HttpContext.User de la solicitud de negociación estarán reservadas. Se puede acceder a ellos en Hub.Context.User.