Caminhoneiro

Controller websockets

Dec 10th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. public class DatabaseNotificationController : ApiController  
  2. {  
  3. public HttpResponseMessage Get()  
  4. {  
  5. HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler());  
  6. return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);  
  7. }  
  8. class ChatWebSocketHandler : Microsoft.Web.WebSockets.WebSocketHandler  
  9. {  
  10. public ChatWebSocketHandler()  
  11. {  
  12. SetupNotifier();  
  13. }  
  14. protected void SetupNotifier()  
  15. {  
  16. using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))  
  17. {  
  18. connection.Open();  
  19. using (SqlCommand command = new SqlCommand(@"SELECT [FullName],[experiance_nYears] FROM [dbo].[t_Doctor]", connection))  
  20. {  
  21. command.Notification = null;  
  22. SqlDependency dependency = new SqlDependency(command);  
  23. dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  
  24. if (connection.State == ConnectionState.Closed)  
  25. {  
  26. connection.Open();  
  27. }  
  28. var reader = command.ExecuteReader();  
  29.                         reader.Close();  
  30.                     }  
  31.                 }  
  32.             }  
  33.  
  34.             private static WebSocketCollection _chatClients = new WebSocketCollection();  
  35.  
  36.             public override void OnOpen()  
  37.             {  
  38.                 _chatClients.Add(this);  
  39.             }  
  40.  
  41.             public override void OnMessage(string msg)  
  42.             {  
  43.                  
  44.             }  
  45.  
  46.             private void dependency_OnChange(object sender, SqlNotificationEventArgs e)  
  47.             {  
  48.                 _chatClients.Broadcast(string.Format("Data changed on {0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));  
  49.                 SetupNotifier();  
  50.             }  
  51.         }  
  52.  
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment