WebSocketServer.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Microsoft.Extensions.Logging;
  15. using Newtonsoft.Json;
  16. using SuperSocket.Common;
  17. using SuperSocket.SocketBase;
  18. using SuperSocket.SocketBase.Command;
  19. using SuperSocket.SocketBase.Config;
  20. using SuperSocket.SocketBase.Protocol;
  21. using SuperWebSocket.Command;
  22. using SuperWebSocket.Config;
  23. using SuperWebSocket.Protocol;
  24. using SuperWebSocket.SubProtocol;
  25. namespace SuperWebSocket
  26. {
  27. /// <summary>
  28. /// WebSocket server interface
  29. /// </summary>
  30. public interface IWebSocketServer : IAppServer
  31. {
  32. /// <summary>
  33. /// Gets the web socket protocol processor.
  34. /// </summary>
  35. IProtocolProcessor WebSocketProtocolProcessor { get; }
  36. /// <summary>
  37. /// Validates the handshake request.
  38. /// </summary>
  39. /// <param name="session">The session.</param>
  40. /// <param name="origin">The origin.</param>
  41. /// <returns>the validation result</returns>
  42. bool ValidateHandshake(IWebSocketSession session, string origin);
  43. }
  44. /// <summary>
  45. /// WebSocket AppServer
  46. /// </summary>
  47. public class WebSocketServer : WebSocketServer<WebSocketSession>
  48. {
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  51. /// </summary>
  52. /// <param name="subProtocols">The sub protocols.</param>
  53. public WebSocketServer(IEnumerable<ISubProtocol<WebSocketSession>> subProtocols)
  54. : base(subProtocols)
  55. {
  56. }
  57. /// <summary>
  58. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  59. /// </summary>
  60. /// <param name="subProtocol">The sub protocol.</param>
  61. public WebSocketServer(ISubProtocol<WebSocketSession> subProtocol)
  62. : base(subProtocol)
  63. {
  64. }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
  67. /// </summary>
  68. public WebSocketServer()
  69. : base(new List<ISubProtocol<WebSocketSession>>())
  70. {
  71. }
  72. }
  73. /// <summary>
  74. /// WebSocket AppServer
  75. /// </summary>
  76. /// <typeparam name="TWebSocketSession">The type of the web socket session.</typeparam>
  77. public abstract class WebSocketServer<TWebSocketSession> : AppServer<TWebSocketSession, IWebSocketFragment>, IWebSocketServer
  78. where TWebSocketSession : WebSocketSession<TWebSocketSession>, new()
  79. {
  80. private IBinaryDataConverter m_BinaryDataConverter;
  81. /// <summary>
  82. /// Gets or sets the binary data converter.
  83. /// </summary>
  84. /// <value>
  85. /// The binary data converter.
  86. /// </value>
  87. protected IBinaryDataConverter BinaryDataConverter
  88. {
  89. get { return m_BinaryDataConverter; }
  90. set { m_BinaryDataConverter = value; }
  91. }
  92. /// <summary>
  93. /// Initializes a new instance of the <see cref="WebSocketServer&lt;TWebSocketSession&gt;"/> class.
  94. /// </summary>
  95. /// <param name="subProtocols">The sub protocols.</param>
  96. public WebSocketServer(IEnumerable<ISubProtocol<TWebSocketSession>> subProtocols)
  97. : this()
  98. {
  99. if (!subProtocols.Any())
  100. return;
  101. foreach (var protocol in subProtocols)
  102. {
  103. if (!RegisterSubProtocolInternal(protocol))
  104. throw new Exception("Failed to register sub protocol!");
  105. }
  106. m_SubProtocolConfigured = true;
  107. }
  108. /// <summary>
  109. /// Initializes a new instance of the <see cref="WebSocketServer&lt;TWebSocketSession&gt;"/> class.
  110. /// </summary>
  111. /// <param name="subProtocol">The sub protocol.</param>
  112. public WebSocketServer(ISubProtocol<TWebSocketSession> subProtocol)
  113. : this(new List<ISubProtocol<TWebSocketSession>> { subProtocol })
  114. {
  115. }
  116. /// <summary>
  117. /// Initializes a new instance of the <see cref="WebSocketServer&lt;TWebSocketSession&gt;"/> class.
  118. /// </summary>
  119. public WebSocketServer()
  120. : base(new WebSocketProtocol())
  121. {
  122. }
  123. //static private ILogger logger;
  124. private Dictionary<string, ISubProtocol<TWebSocketSession>> m_SubProtocols = new Dictionary<string, ISubProtocol<TWebSocketSession>>(StringComparer.OrdinalIgnoreCase);
  125. internal ISubProtocol<TWebSocketSession> DefaultSubProtocol { get; private set; }
  126. private bool m_SubProtocolConfigured = false;
  127. private ConcurrentQueue<TWebSocketSession> m_OpenHandshakePendingQueue = new ConcurrentQueue<TWebSocketSession>();
  128. private ConcurrentQueue<TWebSocketSession> m_CloseHandshakePendingQueue = new ConcurrentQueue<TWebSocketSession>();
  129. /// <summary>
  130. /// The openning handshake timeout, in seconds
  131. /// </summary>
  132. private int m_OpenHandshakeTimeOut;
  133. /// <summary>
  134. /// The closing handshake timeout, in seconds
  135. /// </summary>
  136. private int m_CloseHandshakeTimeOut;
  137. /// <summary>
  138. /// The interval of checking handshake pending queue, in seconds
  139. /// </summary>
  140. private int m_HandshakePendingQueueCheckingInterval;
  141. private Timer m_HandshakePendingQueueCheckingTimer;
  142. /// <summary>
  143. /// Gets the sub protocol by sub protocol name.
  144. /// </summary>
  145. /// <param name="name">The name.</param>
  146. /// <returns></returns>
  147. internal ISubProtocol<TWebSocketSession> GetSubProtocol(string name)
  148. {
  149. ISubProtocol<TWebSocketSession> subProtocol;
  150. if (m_SubProtocols.TryGetValue(name, out subProtocol))
  151. return subProtocol;
  152. else
  153. return null;
  154. }
  155. private IProtocolProcessor m_WebSocketProtocolProcessor;
  156. IProtocolProcessor IWebSocketServer.WebSocketProtocolProcessor
  157. {
  158. get { return m_WebSocketProtocolProcessor; }
  159. }
  160. /// <summary>
  161. /// Gets the request filter factory.
  162. /// </summary>
  163. public new WebSocketProtocol ReceiveFilterFactory
  164. {
  165. get
  166. {
  167. return (WebSocketProtocol)base.ReceiveFilterFactory;
  168. }
  169. }
  170. /// <summary>
  171. /// Register sub protocols, Only use after empty create
  172. /// </summary>
  173. /// <param name="subProtocols"></param>
  174. /// <exception cref="Exception"></exception>
  175. public void RegisterSubProtocol(IEnumerable<ISubProtocol<TWebSocketSession>> subProtocols)
  176. {
  177. if (!subProtocols.Any())
  178. return;
  179. foreach (var protocol in subProtocols)
  180. {
  181. if (!RegisterSubProtocolInternal(protocol))
  182. throw new Exception("Failed to register sub protocol!");
  183. }
  184. m_SubProtocolConfigured = true;
  185. }
  186. bool IWebSocketServer.ValidateHandshake(IWebSocketSession session, string origin)
  187. {
  188. var s = (TWebSocketSession)session;
  189. s.Origin = origin;
  190. return ValidateHandshake(s, origin);
  191. }
  192. /// <summary>
  193. /// Validates the handshake request.
  194. /// </summary>
  195. /// <param name="session">The session.</param>
  196. /// <param name="origin">The origin in the handshake request.</param>
  197. /// <returns></returns>
  198. protected virtual bool ValidateHandshake(TWebSocketSession session, string origin)
  199. {
  200. return true;
  201. }
  202. bool RegisterSubProtocolInternal(ISubProtocol<TWebSocketSession> subProtocol)
  203. {
  204. if (m_SubProtocols.ContainsKey(subProtocol.Name))
  205. {
  206. Logger.LogError("Cannot register duplicate name sub protocol! Duplicate name: {0}.", subProtocol.Name);
  207. return false;
  208. }
  209. m_SubProtocols.Add(subProtocol.Name, subProtocol);
  210. return true;
  211. }
  212. private bool SetupSubProtocols(IServerConfig config)
  213. {
  214. //Preparing sub protocols' configuration
  215. var subProtocolConfigSection = config.GetChildConfig<SubProtocolConfigCollection>("subProtocols");
  216. var subProtocolConfigDict = new Dictionary<string, SubProtocolConfig>(subProtocolConfigSection == null ? 0 : subProtocolConfigSection.Count, StringComparer.OrdinalIgnoreCase);
  217. if (subProtocolConfigSection != null)
  218. {
  219. foreach (var protocolConfig in subProtocolConfigSection)
  220. {
  221. string originalProtocolName = protocolConfig.Name;
  222. string protocolName;
  223. ISubProtocol<TWebSocketSession> subProtocolInstance;
  224. if (!string.IsNullOrEmpty(originalProtocolName))
  225. {
  226. protocolName = originalProtocolName;
  227. if (!string.IsNullOrEmpty(protocolConfig.Type))
  228. {
  229. try
  230. {
  231. subProtocolInstance = AssemblyUtil.CreateInstance<ISubProtocol<TWebSocketSession>>(protocolConfig.Type, new object[] { originalProtocolName });
  232. }
  233. catch (Exception e)
  234. {
  235. Logger.LogError(e.Message);
  236. return false;
  237. }
  238. if (!RegisterSubProtocolInternal(subProtocolInstance))
  239. return false;
  240. }
  241. else
  242. {
  243. if (!m_SubProtocols.ContainsKey(protocolName))
  244. {
  245. subProtocolInstance = new BasicSubProtocol<TWebSocketSession>(protocolName);
  246. if (!RegisterSubProtocolInternal(subProtocolInstance))
  247. return false;
  248. }
  249. }
  250. }
  251. else
  252. {
  253. protocolName = BasicSubProtocol<TWebSocketSession>.DefaultName;
  254. if (!string.IsNullOrEmpty(protocolConfig.Type))
  255. {
  256. Logger.LogError("You needn't set Type attribute for SubProtocol, if you don't set Name attribute!");
  257. return false;
  258. }
  259. }
  260. subProtocolConfigDict[protocolName] = protocolConfig;
  261. }
  262. if (subProtocolConfigDict.Values.Any())
  263. m_SubProtocolConfigured = true;
  264. }
  265. if (m_SubProtocols.Count <= 0 || (subProtocolConfigDict.ContainsKey(BasicSubProtocol<TWebSocketSession>.DefaultName) && !m_SubProtocols.ContainsKey(BasicSubProtocol<TWebSocketSession>.DefaultName)))
  266. {
  267. if (!RegisterSubProtocolInternal(BasicSubProtocol<TWebSocketSession>.CreateDefaultSubProtocol()))
  268. return false;
  269. }
  270. //Initialize sub protocols
  271. foreach (var subProtocol in m_SubProtocols.Values)
  272. {
  273. SubProtocolConfig protocolConfig = null;
  274. subProtocolConfigDict.TryGetValue(subProtocol.Name, out protocolConfig);
  275. bool initialized = false;
  276. try
  277. {
  278. initialized = subProtocol.Initialize(this, protocolConfig, Logger);
  279. }
  280. catch (Exception e)
  281. {
  282. initialized = false;
  283. Logger.LogError(e,e.Message);
  284. }
  285. if (!initialized)
  286. {
  287. Logger.LogError("Failed to initialize the sub protocol '{0}'!", subProtocol.Name);
  288. return false;
  289. }
  290. }
  291. return true;
  292. }
  293. /// <summary>
  294. /// Setups with the specified root config.
  295. /// </summary>
  296. /// <param name="rootConfig">The root config.</param>
  297. /// <param name="config">The config.</param>
  298. /// <returns></returns>
  299. protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
  300. {
  301. if (m_SubProtocols != null && m_SubProtocols.Count > 0)
  302. DefaultSubProtocol = m_SubProtocols.Values.FirstOrDefault();
  303. m_WebSocketProtocolProcessor = new DraftHybi10Processor
  304. {
  305. NextProcessor = new Rfc6455Processor
  306. {
  307. NextProcessor = new DraftHybi00Processor()
  308. }
  309. };
  310. SetupMultipleProtocolSwitch(m_WebSocketProtocolProcessor);
  311. if (!int.TryParse(config.Options.GetValue("handshakePendingQueueCheckingInterval"), out m_HandshakePendingQueueCheckingInterval))
  312. m_HandshakePendingQueueCheckingInterval = 60;// 1 minute default
  313. if (!int.TryParse(config.Options.GetValue("openHandshakeTimeOut"), out m_OpenHandshakeTimeOut))
  314. m_OpenHandshakeTimeOut = 120;// 2 minute default
  315. if (!int.TryParse(config.Options.GetValue("closeHandshakeTimeOut"), out m_CloseHandshakeTimeOut))
  316. m_CloseHandshakeTimeOut = 120;// 2 minute default
  317. if (m_BinaryDataConverter == null)
  318. {
  319. m_BinaryDataConverter = new TextEncodingBinaryDataConverter(Encoding.UTF8);
  320. }
  321. return true;
  322. }
  323. private void SetupMultipleProtocolSwitch(IProtocolProcessor rootProcessor)
  324. {
  325. var thisProcessor = rootProcessor;
  326. List<int> availableVersions = new List<int>();
  327. while (true)
  328. {
  329. if (thisProcessor.Version > 0)
  330. availableVersions.Add(thisProcessor.Version);
  331. if (thisProcessor.NextProcessor == null)
  332. break;
  333. thisProcessor = thisProcessor.NextProcessor;
  334. }
  335. thisProcessor.NextProcessor = new MultipleProtocolSwitchProcessor(availableVersions.ToArray());
  336. }
  337. /// <summary>
  338. /// Called when [started].
  339. /// </summary>
  340. protected override void OnStarted()
  341. {
  342. m_HandshakePendingQueueCheckingTimer = new Timer(HandshakePendingQueueCheckingCallback, null, m_HandshakePendingQueueCheckingInterval * 1000, m_HandshakePendingQueueCheckingInterval * 1000);
  343. base.OnStarted();
  344. }
  345. private void HandshakePendingQueueCheckingCallback(object state)
  346. {
  347. try
  348. {
  349. m_HandshakePendingQueueCheckingTimer.Change(Timeout.Infinite, Timeout.Infinite);
  350. while (true)
  351. {
  352. TWebSocketSession session;
  353. if (!m_OpenHandshakePendingQueue.TryPeek(out session))
  354. break;
  355. if (session.Handshaked || !session.Connected)
  356. {
  357. //Handshaked or not connected
  358. m_OpenHandshakePendingQueue.TryDequeue(out session);
  359. continue;
  360. }
  361. if (DateTime.UtcNow < session.StartTime.AddSeconds(m_OpenHandshakeTimeOut))
  362. break;
  363. //Timeout, dequeue and then close
  364. m_OpenHandshakePendingQueue.TryDequeue(out session);
  365. session.Close(CloseReason.TimeOut);
  366. }
  367. while (true)
  368. {
  369. TWebSocketSession session;
  370. if (!m_CloseHandshakePendingQueue.TryPeek(out session))
  371. break;
  372. if (!session.Connected)
  373. {
  374. //the session has been closed
  375. m_CloseHandshakePendingQueue.TryDequeue(out session);
  376. continue;
  377. }
  378. if (DateTime.UtcNow < session.StartClosingHandshakeTime.AddSeconds(m_CloseHandshakeTimeOut))
  379. break;
  380. //Timeout, dequeue and then close
  381. m_CloseHandshakePendingQueue.TryDequeue(out session);
  382. //Needn't send closing handshake again
  383. session.Close(CloseReason.ServerClosing);
  384. }
  385. }
  386. catch (Exception e)
  387. {
  388. Logger.LogError(e,e.Message);
  389. }
  390. finally
  391. {
  392. m_HandshakePendingQueueCheckingTimer.Change(m_HandshakePendingQueueCheckingInterval * 1000, m_HandshakePendingQueueCheckingInterval * 1000);
  393. }
  394. }
  395. internal void PushToCloseHandshakeQueue(IAppSession appSession)
  396. {
  397. m_CloseHandshakePendingQueue.Enqueue((TWebSocketSession)appSession);
  398. }
  399. /// <summary>
  400. /// Called when [new session connected].
  401. /// </summary>
  402. /// <param name="session">The session.</param>
  403. protected override void OnNewSessionConnected(TWebSocketSession session)
  404. {
  405. m_OpenHandshakePendingQueue.Enqueue(session);
  406. }
  407. internal void FireOnNewSessionConnected(IAppSession appSession)
  408. {
  409. base.OnNewSessionConnected((TWebSocketSession)appSession);
  410. }
  411. /// <summary>
  412. /// Occurs when [new request received].
  413. /// </summary>
  414. /// <exception cref="System.NotSupportedException"></exception>
  415. [Browsable(false)]
  416. [EditorBrowsable(EditorBrowsableState.Never)]
  417. public override event RequestHandler<TWebSocketSession, IWebSocketFragment> NewRequestReceived
  418. {
  419. add { throw new NotSupportedException("Please use NewMessageReceived instead!"); }
  420. remove { throw new NotSupportedException("Please use NewMessageReceived instead!"); }
  421. }
  422. private SessionHandler<TWebSocketSession, string> m_NewMessageReceived;
  423. /// <summary>
  424. /// Occurs when [new message received].
  425. /// </summary>
  426. public event SessionHandler<TWebSocketSession, string> NewMessageReceived
  427. {
  428. add
  429. {
  430. if (m_SubProtocolConfigured)
  431. throw new Exception("If you have defined any sub protocol, you cannot subscribe NewMessageReceived event!");
  432. m_NewMessageReceived += value;
  433. }
  434. remove
  435. {
  436. m_NewMessageReceived -= value;
  437. }
  438. }
  439. void ExecuteMessage(TWebSocketSession session, string message)
  440. {
  441. if (session.SubProtocol == null)
  442. {
  443. Logger.LogError("No SubProtocol selected! This session cannot process any message!");
  444. session.CloseWithHandshake(session.ProtocolProcessor.CloseStatusClode.ProtocolError, "No SubProtocol selected");
  445. return;
  446. }
  447. ExecuteSubCommand(session, session.SubProtocol.SubRequestParser.ParseRequestInfo(message));
  448. }
  449. internal void OnNewMessageReceived(TWebSocketSession session, string message)
  450. {
  451. try
  452. {
  453. if (m_NewMessageReceived == null)
  454. {
  455. ExecuteMessage(session, message);
  456. }
  457. else
  458. {
  459. m_NewMessageReceived(session, message);
  460. }
  461. }
  462. catch (Exception ex)
  463. {
  464. Logger.LogError(message + " " + ex.ToString());
  465. }
  466. }
  467. private SessionHandler<TWebSocketSession, byte[]> m_NewDataReceived;
  468. /// <summary>
  469. /// Occurs when [new data received].
  470. /// </summary>
  471. public event SessionHandler<TWebSocketSession, byte[]> NewDataReceived
  472. {
  473. add
  474. {
  475. m_NewDataReceived += value;
  476. }
  477. remove
  478. {
  479. m_NewDataReceived -= value;
  480. }
  481. }
  482. internal void OnNewDataReceived(TWebSocketSession session, byte[] data)
  483. {
  484. if (m_NewDataReceived == null)
  485. {
  486. var converter = m_BinaryDataConverter;
  487. if (converter != null)
  488. {
  489. ExecuteMessage(session, converter.ToString(data, 0, data.Length));
  490. }
  491. return;
  492. }
  493. m_NewDataReceived(session, data);
  494. }
  495. private const string m_Tab = "\t";
  496. private const char m_Colon = ':';
  497. private const string m_Space = " ";
  498. private const char m_SpaceChar = ' ';
  499. private const string m_ValueSeparator = ", ";
  500. internal static void ParseHandshake(IWebSocketSession session, TextReader reader)
  501. {
  502. string line;
  503. string firstLine = string.Empty;
  504. string prevKey = string.Empty;
  505. //logger.LogInformation("============================================================");
  506. while (!string.IsNullOrEmpty(line = reader.ReadLine()))
  507. {
  508. //logger.LogInformation(session.SessionID + " " + line);
  509. if (string.IsNullOrEmpty(firstLine))
  510. {
  511. firstLine = line;
  512. continue;
  513. }
  514. if (line.StartsWith(m_Tab) && !string.IsNullOrEmpty(prevKey))
  515. {
  516. string currentValue = session.Items.GetValue<string>(prevKey, string.Empty);
  517. session.Items[prevKey] = currentValue + line.Trim();
  518. continue;
  519. }
  520. int pos = line.IndexOf(m_Colon);
  521. if (pos <= 0)
  522. continue;
  523. string key = line.Substring(0, pos);
  524. if (!string.IsNullOrEmpty(key))
  525. key = key.Trim();
  526. var valueOffset = pos + 1;
  527. if (line.Length <= valueOffset) //No value in this line
  528. continue;
  529. string value = line.Substring(valueOffset);
  530. if (!string.IsNullOrEmpty(value) && value.StartsWith(m_Space) && value.Length > 1)
  531. value = value.Substring(1);
  532. if (string.IsNullOrEmpty(key))
  533. continue;
  534. object oldValue;
  535. if (!session.Items.TryGetValue(key, out oldValue))
  536. {
  537. session.Items.Add(key, value);
  538. }
  539. else
  540. {
  541. session.Items[key] = oldValue + m_ValueSeparator + value;
  542. }
  543. prevKey = key;
  544. }
  545. //logger.LogInformation("============================================================");
  546. var metaInfo = firstLine.Split(m_SpaceChar);
  547. session.Method = metaInfo[0];
  548. session.Path = metaInfo[1];
  549. session.HttpVersion = metaInfo[2];
  550. }
  551. /// <summary>
  552. /// Setups the commands.
  553. /// </summary>
  554. /// <param name="discoveredCommands">The discovered commands.</param>
  555. /// <returns></returns>
  556. protected override bool SetupCommands(Dictionary<string, ICommand<TWebSocketSession, IWebSocketFragment>> discoveredCommands)
  557. {
  558. var commands = new List<ICommand<TWebSocketSession, IWebSocketFragment>>
  559. {
  560. new HandShake<TWebSocketSession>(),
  561. new Text<TWebSocketSession>(),
  562. new Binary<TWebSocketSession>(),
  563. new Close<TWebSocketSession>(),
  564. new Ping<TWebSocketSession>(),
  565. new Pong<TWebSocketSession>(),
  566. new Continuation<TWebSocketSession>(),
  567. new Plain<TWebSocketSession>()
  568. };
  569. commands.ForEach(c => discoveredCommands.Add(c.Name, c));
  570. if (!SetupSubProtocols(Config))
  571. return false;
  572. return true;
  573. }
  574. /// <summary>
  575. /// Executes the command.
  576. /// </summary>
  577. /// <param name="session">The session.</param>
  578. /// <param name="requestInfo">The request info.</param>
  579. protected override void ExecuteCommand(TWebSocketSession session, IWebSocketFragment requestInfo)
  580. {
  581. if (session.InClosing)
  582. {
  583. //Only handle closing handshake if the session is in closing
  584. if (requestInfo.Key != OpCode.CloseTag)
  585. return;
  586. }
  587. base.ExecuteCommand(session, requestInfo);
  588. }
  589. private void ExecuteSubCommand(TWebSocketSession session, SubRequestInfo requestInfo)
  590. {
  591. ISubCommand<TWebSocketSession> subCommand;
  592. if (session.SubProtocol.TryGetCommand(requestInfo.Key, out subCommand))
  593. {
  594. session.CurrentCommand = requestInfo.Key;
  595. subCommand.ExecuteCommand(session, requestInfo);
  596. session.PrevCommand = requestInfo.Key;
  597. Logger.LogInfo(session, string.Format("Command - {0} - {1}", session.SessionID, requestInfo.Key));
  598. }
  599. else
  600. {
  601. //session.SubProtocol.TryGetCommand("OCPP", out subCommand);
  602. //session.CurrentCommand = "OCPP";
  603. //subCommand.ExecuteCommand(session, requestInfo);
  604. //session.PrevCommand = "OCPP";
  605. session.HandleUnknownCommand(requestInfo);
  606. }
  607. session.LastActiveTime = DateTime.UtcNow;
  608. }
  609. /// <summary>
  610. /// Broadcasts data to the specified sessions.
  611. /// </summary>
  612. /// <param name="sessions">The sessions.</param>
  613. /// <param name="data">The data.</param>
  614. /// <param name="offset">The offset.</param>
  615. /// <param name="length">The length.</param>
  616. /// <param name="sendFeedback">The send feedback.</param>
  617. public void Broadcast(IEnumerable<TWebSocketSession> sessions, byte[] data, int offset, int length, Action<TWebSocketSession, bool> sendFeedback)
  618. {
  619. IList<ArraySegment<byte>> encodedPackage = null;
  620. IProtocolProcessor encodingProcessor = null;
  621. foreach (var s in sessions)
  622. {
  623. if (!s.Connected)
  624. continue;
  625. var currentProtocolProcessor = s.ProtocolProcessor;
  626. if (currentProtocolProcessor == null || !currentProtocolProcessor.CanSendBinaryData)
  627. continue;
  628. if (encodedPackage == null || currentProtocolProcessor != encodingProcessor)
  629. {
  630. encodedPackage = currentProtocolProcessor.GetEncodedPackage(OpCode.Binary, data, offset, length);
  631. encodingProcessor = currentProtocolProcessor;
  632. }
  633. Task.Factory.StartNew(SendRawDataToSession, new BroadcastState(s, encodedPackage, sendFeedback));
  634. }
  635. }
  636. /// <summary>
  637. /// Broadcasts message to the specified sessions.
  638. /// </summary>
  639. /// <param name="sessions">The sessions.</param>
  640. /// <param name="message">The message.</param>
  641. /// <param name="sendFeedback">The send feedback.</param>
  642. public void Broadcast(IEnumerable<TWebSocketSession> sessions, string message, Action<TWebSocketSession, bool> sendFeedback)
  643. {
  644. IList<ArraySegment<byte>> encodedPackage = null;
  645. IProtocolProcessor encodingProcessor = null;
  646. foreach (var s in sessions)
  647. {
  648. if (!s.Connected)
  649. continue;
  650. var currentProtocolProcessor = s.ProtocolProcessor;
  651. if (currentProtocolProcessor == null)
  652. continue;
  653. if (encodedPackage == null || encodingProcessor != currentProtocolProcessor)
  654. {
  655. encodedPackage = currentProtocolProcessor.GetEncodedPackage(OpCode.Text, message);
  656. encodingProcessor = currentProtocolProcessor;
  657. }
  658. Task.Factory.StartNew(SendRawDataToSession, new BroadcastState(s, encodedPackage, sendFeedback));
  659. }
  660. }
  661. private void SendRawDataToSession(object state)
  662. {
  663. var param = state as BroadcastState;
  664. var session = param.Session;
  665. var sendFeedback = param.FeedbackFunc;
  666. var sendOk = false;
  667. try
  668. {
  669. sendOk = session.TrySendRawData(param.Data);
  670. }
  671. catch (Exception e)
  672. {
  673. session.Logger.LogError(e,e.Message);
  674. }
  675. sendFeedback(session, sendOk);
  676. }
  677. #region JSON serialize/deserialize
  678. /// <summary>
  679. /// Serialize the target object by JSON
  680. /// </summary>
  681. /// <param name="target">The target.</param>
  682. /// <returns></returns>
  683. public virtual string JsonSerialize(object target)
  684. {
  685. return JsonConvert.SerializeObject(target);
  686. }
  687. /// <summary>
  688. /// Deserialize the JSON string to target type object.
  689. /// </summary>
  690. /// <param name="json">The json.</param>
  691. /// <param name="type">The type.</param>
  692. /// <returns></returns>
  693. public virtual object JsonDeserialize(string json, Type type)
  694. {
  695. return JsonConvert.DeserializeObject(json, type);
  696. }
  697. #endregion
  698. class BroadcastState
  699. {
  700. public TWebSocketSession Session { get; private set; }
  701. public IList<ArraySegment<byte>> Data { get; private set; }
  702. public Action<TWebSocketSession, bool> FeedbackFunc { get; private set; }
  703. public BroadcastState(TWebSocketSession session, IList<ArraySegment<byte>> data, Action<TWebSocketSession, bool> feedbackFunc)
  704. {
  705. Session = session;
  706. Data = data;
  707. FeedbackFunc = feedbackFunc;
  708. }
  709. }
  710. }
  711. }