Friday, February 3, 2017

Websockets using OWIN

Leave a Comment

All the examples using Microsoft WebSockets over a web-api that I've seen so far use IIS, the implementation is on the get method the HTTP connection is upgraded to a websocket and an instance of websocket handler is passed to the HTTPContext

public HttpResponseMessage Get() {   if (HttpContext.Current.IsWebSocketRequest) {      var noteHandler = new NoteSocketHandler();      HttpContext.Current.AcceptWebSocketRequest(noteHandler);   }   return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); } 

What am trying to achieve is to do the same on an OWIN pipeline. The problem am facing is the connection is being upgraded to use Websockets but it is not utilizing my websocket handler. Where am I going wrong? Please suggest.

Controller utilizing OwinContext (Followed the example WebSockets in Nancy using OWIN),

public HttpResponseMessage Get() {    IOwinContext owinContext = Request.GetOwinContext();     WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");    if (acceptToken != null) {       var requestHeaders = GetValue<IDictionary<string, string[]>>(owinContext.Environment, "owin.RequestHeaders");        Dictionary<string, object> acceptOptions = null;       string[] subProtocols;       if (requestHeaders.TryGetValue("Sec-WebSocket-Protocol", out subProtocols) && subProtocols.Length > 0) {          acceptOptions = new Dictionary<string, object>();          // Select the first one from the client          acceptOptions.Add("websocket.SubProtocol", subProtocols[0].Split(',').First().Trim());       }        acceptToken(acceptOptions, async wsEnv => {          var wsSendAsync = (WebSocketSendAsync)wsEnv["websocket.SendAsync"];          var wsRecieveAsync = (WebSocketReceiveAsync)wsEnv["websocket.ReceiveAsync"];          var wsCloseAsync = (WebSocketCloseAsync)wsEnv["websocket.CloseAsync"];          var wsCallCancelled = (CancellationToken)wsEnv["websocket.CallCancelled"];           //should I pass the handler to an event?          var handler = new NoteSocketHAndler();                      });     } else {       return new HttpResponseMessage(HttpStatusCode.BadRequest);    }    return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); } 

Handler Code:

using System; using Socket = Microsoft.Web.WebSockets; using Newtonsoft.Json;  public class NoteSocketHandler : Socket.WebSocketHandler {    private static Socket.WebSocketCollection connections = new Socket.WebSocketCollection();     public NoteSocketHandler() {    }     public override void OnOpen() {       connections.Add(this);    }     public override void OnClose() {       connections.Remove(this);    }     public override void OnMessage(string message) {       ChatMessage chatMessage = JsonConvert.DeserializeObject<ChatMessage>(message);       foreach (var connection in connections) {          connection.Send(message);       }    } } 

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment