WebSocketServerBase.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. #region MIT License
  2. /**
  3. * WebSocketServerBase.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012 sta.blockhead
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #endregion
  28. using System;
  29. using System.Diagnostics;
  30. using System.Net;
  31. using System.Net.Sockets;
  32. using System.Threading;
  33. namespace WebSocketSharp.Server
  34. {
  35. public abstract class WebSocketServerBase
  36. {
  37. #region Fields
  38. private Thread _acceptClientThread;
  39. private IPAddress _address;
  40. private bool _isSecure;
  41. private bool _isSelfHost;
  42. private int _port;
  43. private TcpListener _tcpListener;
  44. private Uri _uri;
  45. #endregion
  46. #region Constructors
  47. protected WebSocketServerBase()
  48. {
  49. _isSelfHost = false;
  50. }
  51. protected WebSocketServerBase(string url)
  52. {
  53. if (url == null)
  54. throw new ArgumentNullException("url");
  55. Uri uri;
  56. string msg;
  57. if (!tryCreateUri(url, out uri, out msg))
  58. throw new ArgumentException(msg, "url");
  59. init(uri);
  60. }
  61. protected WebSocketServerBase(IPAddress address, int port, string absPath, bool secure)
  62. {
  63. if (address == null)
  64. throw new ArgumentNullException("address");
  65. if (absPath == null)
  66. throw new ArgumentNullException("absPath");
  67. string msg;
  68. if (!Ext.IsValidAbsolutePath(absPath, out msg))
  69. throw new ArgumentException(msg, "absPath");
  70. if ((port == 80 && secure) ||
  71. (port == 443 && !secure))
  72. {
  73. msg = String.Format(
  74. "Invalid pair of 'port' and 'secure': {0}, {1}", port, secure);
  75. throw new ArgumentException(msg);
  76. }
  77. _address = address;
  78. _port = port > 0
  79. ? port
  80. : secure ? 443 : 80;
  81. _uri = Ext.ToUri(absPath);
  82. _isSecure = secure;
  83. init();
  84. }
  85. #endregion
  86. #region Protected Property
  87. protected Uri BaseUri
  88. {
  89. get
  90. {
  91. return _uri;
  92. }
  93. set
  94. {
  95. _uri = value;
  96. }
  97. }
  98. #endregion
  99. #region Public Properties
  100. public IPAddress Address
  101. {
  102. get
  103. {
  104. return _address;
  105. }
  106. }
  107. public bool IsSecure
  108. {
  109. get
  110. {
  111. return _isSecure;
  112. }
  113. }
  114. public bool IsSelfHost
  115. {
  116. get
  117. {
  118. return _isSelfHost;
  119. }
  120. }
  121. public int Port
  122. {
  123. get
  124. {
  125. return _port;
  126. }
  127. }
  128. #endregion
  129. #region Events
  130. public event EventHandler<ErrorEventArgs> OnError;
  131. #endregion
  132. #region Private Methods
  133. private void acceptClient()
  134. {
  135. while (true)
  136. {
  137. try
  138. {
  139. var client = _tcpListener.AcceptTcpClient();
  140. acceptSocketAsync(client);
  141. }
  142. catch (SocketException)
  143. {
  144. // TcpListener has been stopped.
  145. break;
  146. }
  147. catch (Exception ex)
  148. {
  149. onError(ex.Message);
  150. break;
  151. }
  152. }
  153. }
  154. private void acceptSocketAsync(TcpClient client)
  155. {
  156. WaitCallback acceptSocketCb = (state) =>
  157. {
  158. try
  159. {
  160. AcceptWebSocket(client);
  161. }
  162. catch (Exception ex)
  163. {
  164. onError(ex.Message);
  165. }
  166. };
  167. ThreadPool.QueueUserWorkItem(acceptSocketCb);
  168. }
  169. private void init()
  170. {
  171. _tcpListener = new TcpListener(_address, _port);
  172. _isSelfHost = true;
  173. }
  174. private void init(Uri uri)
  175. {
  176. var scheme = uri.Scheme;
  177. var host = uri.DnsSafeHost;
  178. var port = uri.Port;
  179. var addrs = Dns.GetHostAddresses(host);
  180. _uri = uri;
  181. _address = addrs[0];
  182. _isSecure = scheme == "wss" ? true : false;
  183. _port = port > 0
  184. ? port
  185. : _isSecure ? 443 : 80;
  186. init();
  187. }
  188. private void onError(string message)
  189. {
  190. #if DEBUG
  191. var callerFrame = new StackFrame(1);
  192. var caller = callerFrame.GetMethod();
  193. Console.WriteLine("WSSV: Error@{0}: {1}", caller.Name, message);
  194. #endif
  195. Ext.Emit(OnError, this, new ErrorEventArgs(message));
  196. }
  197. private void startAcceptClientThread()
  198. {
  199. _acceptClientThread = new Thread(new ThreadStart(acceptClient));
  200. _acceptClientThread.IsBackground = true;
  201. _acceptClientThread.Start();
  202. }
  203. private bool tryCreateUri(string uriString, out Uri result, out string message)
  204. {
  205. if (!Ext.TryCreateWebSocketUri(uriString, out result, out message))
  206. return false;
  207. if (!Ext.IsNullOrEmpty(result.Query))
  208. {
  209. result = null;
  210. message = "Must not contain the query component: " + uriString;
  211. return false;
  212. }
  213. return true;
  214. }
  215. #endregion
  216. #region Protected Methods
  217. protected abstract void AcceptWebSocket(TcpClient client);
  218. protected virtual void Error(string message)
  219. {
  220. onError(message);
  221. }
  222. #endregion
  223. #region Public Methods
  224. public virtual void Start()
  225. {
  226. if (!_isSelfHost)
  227. return;
  228. _tcpListener.Start();
  229. startAcceptClientThread();
  230. }
  231. public virtual void Stop()
  232. {
  233. if (!_isSelfHost)
  234. return;
  235. _tcpListener.Stop();
  236. _acceptClientThread.Join(5 * 1000);
  237. }
  238. #endregion
  239. }
  240. }