ryanhelms1

Untitled

Jul 19th, 2018
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. The following steps describe how to connect azure SignalR service in ASP.NET core. See Azure SignalR samples for more samples.
  2. First, you are going to need to use SignalR in ConfigureServices. It looks like the following:
  3. /**
  4. * This sample is for ASP.NET core.
  5. */
  6. public class Startup
  7. {
  8. public Startup(IConfiguration configuration)
  9. {
  10. Configuration = configuration;
  11. }
  12.  
  13. public IConfiguration Configuration { get; }
  14.  
  15. // This method gets called by the runtime. Use this method to add services to the container.
  16. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  17. public void ConfigureServices(IServiceCollection services)
  18. {
  19. services.AddMvc();
  20. services.AddSignalR()
  21. .AddAzureSignalR();
  22. }
  23.  
  24. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  25. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  26. {
  27. app.UseMvc();
  28. app.UseFileServer();
  29. app.UseAzureSignalR(routes =>
  30. {
  31. routes.MapHub("/chat");
  32. });
  33. }
  34. }
  35. And your hub looks like the following:
  36.  
  37. public class Chat : Hub
  38. {
  39. public void BroadcastMessage(string name, string message)
  40. {
  41. Clients.All.SendAsync("broadcastMessage", name, message);
  42. }
  43.  
  44. public void Echo(string name, string message)
  45. {
  46. Clients.Client(Context.ConnectionId).SendAsync("echo", name, message + " (echo from server)");
  47. }
  48. }
  49.  
  50. In your client scripts, using the following logic to get connected to the service:
  51.  
  52. function bindConnectionMessage(connection) {
  53. var messageCallback = function (name, message) {
  54. if (!message) return;
  55. // deal with the message
  56. alert("message received:" + message);
  57. };
  58. // Create a function that the hub can call to broadcast messages.
  59. connection.on('broadcastMessage', messageCallback);
  60. connection.on('echo', messageCallback);
  61. }
  62.  
  63. var connection = new signalR.HubConnectionBuilder()
  64. .withUrl('/chat')
  65. .build();
  66.  
  67. bindConnectionMessage(connection);
  68. connection.start()
  69. .then(function () {
  70. onConnected(connection);
  71. })
  72. .catch(function (error) {
  73. console.error(error.message);
  74. });
Advertisement
Add Comment
Please, Sign In to add comment