Guest User

Untitled

a guest
Aug 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. Send server message to connected clients with Signalr/PersistentConnection
  2. public class MyConnection : PersistentConnection {
  3. protected override Task OnReceivedAsync(string clientId, string data) {
  4. // Broadcast data to all clients
  5. return Connection.Broadcast(data);
  6. }
  7. }
  8.  
  9. using System;
  10. using System.Web.Routing;
  11. using SignalR.Routing;
  12.  
  13. public class Global : System.Web.HttpApplication {
  14. protected void Application_Start(object sender, EventArgs e) {
  15. // Register the route for chat
  16. RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");
  17. }
  18. }
  19.  
  20. $(function () {
  21. var connection = $.connection('echo');
  22.  
  23. connection.received(function (data) {
  24. $('#messages').append('<li>' + data + '</li>');
  25. });
  26.  
  27. connection.start();
  28.  
  29. $("#broadcast").click(function () {
  30. connection.send($('#msg').val());
  31. });
  32. });
  33.  
  34. public bool Join(string channel)
  35. {
  36. AddToGroup(channel.ToString()).Wait();
  37. return true;
  38. }
  39.  
  40. public void Send(string channel, string message)
  41. {
  42.  
  43. String id = this.Context.ClientId;
  44.  
  45. Clients[channel.ToString()].addMessage(message);
  46.  
  47. }
  48.  
  49. using SignalR;
  50. using SignalR.Hosting.AspNet;
  51. using SignalR.Infrastructure;
  52.  
  53. public class MyConnection : PersistentConnection
  54. {
  55. }
  56.  
  57. public class Notifier
  58. {
  59. public void Notify(string clientId, object data) {
  60. MyConnection connection = (MyConnection) AspNetHost.DependencyResolver
  61. .Resolve<IConnectionManager()
  62. .GetConnection<MyConnection>();
  63.  
  64. connection.Send(clientId, data);
  65. }
  66. }
Add Comment
Please, Sign In to add comment