You should consider using he SignalR framework. It offers very comfortable events like OnConnect() and OnDisconnect(). Under the hood it works with
- WebSockets
- Server Sent Events
- Forever Frame
- Long polling
It uses whatever is available with the given environment, starting with WebSockets.