/// <summary> /// Uses the protocol for new TCP connections that request the protocol /// </summary> public void UseProtocol(ITwinoProtocol protocol) { List <ITwinoProtocol> list = Protocols.ToList(); ITwinoProtocol old = list.FirstOrDefault(x => x.Name.Equals(protocol.Name, StringComparison.InvariantCultureIgnoreCase)); if (old != null) { list.Remove(old); } list.Add(protocol); Protocols = list.ToArray(); }
/// <summary> /// Uses WebSocket Protocol and accepts HTTP connections which comes with "Upgrade: websocket" header data /// </summary> public static ITwinoServer UseWebSockets(this ITwinoServer server, IProtocolConnectionHandler <WsServerSocket, WebSocketMessage> handler, HttpOptions options) { //we need http protocol is added ITwinoProtocol http = server.FindProtocol("http"); if (http == null) { TwinoHttpProtocol httpProtocol = new TwinoHttpProtocol(server, new WebSocketHttpHandler(), options); server.UseProtocol(httpProtocol); } TwinoWebSocketProtocol protocol = new TwinoWebSocketProtocol(server, handler); server.UseProtocol(protocol); return(server); }
/// <summary> /// Switches client's protocol to new protocol (finds by name) /// </summary> public async Task SwitchProtocol(IConnectionInfo info, string newProtocolName, ConnectionData data) { foreach (ITwinoProtocol protocol in Protocols) { if (protocol.Name.Equals(newProtocolName, StringComparison.InvariantCultureIgnoreCase)) { ProtocolHandshakeResult hsresult = await protocol.SwitchTo(info, data); if (!hsresult.Accepted) { info.Close(); return; } ITwinoProtocol previous = info.Protocol; info.Protocol = protocol; info.Socket = hsresult.Socket; if (info.Socket != null) { info.Socket.SetOnConnected(); } if (hsresult.Response != null) { await info.GetStream().WriteAsync(hsresult.Response); } if (info.Socket != null) { info.Socket.SetOnProtocolSwitched(previous, info.Protocol); } await protocol.HandleConnection(info, hsresult); return; } } }
/// <summary> /// Triggers virtual protocol switched /// </summary> internal void SetOnProtocolSwitched(ITwinoProtocol previous, ITwinoProtocol current) { OnProtocolSwitched(previous, current); }
/// <summary> /// Called when client's protocol has switched /// </summary> protected virtual void OnProtocolSwitched(ITwinoProtocol previous, ITwinoProtocol current) { //not abstract, override is not must. but we do not have anything to do here. }