You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

446 lines
12 KiB

4 years ago
4 years ago
4 years ago
4 years ago
  1. #if !NET20
  2. using Apewer;
  3. using System;
  4. using System.Collections.Generic;
  5. namespace Apewer.WebSocket
  6. {
  7. /// <summary></summary>
  8. public sealed class GenericServer : IDisposable
  9. {
  10. const string DefaultAddress = "0.0.0.0";
  11. const ushort DefaultPort = 8000;
  12. private Dictionary<int, Connection> _connections = new Dictionary<int, Connection>();
  13. private WebSocketServer _server = null;
  14. private bool _running = false;
  15. private string _address = null;
  16. private int _port = DefaultPort;
  17. /// <summary></summary>
  18. public event SocketEvent OnOpen;
  19. /// <summary></summary>
  20. public event SocketEvent OnClose;
  21. /// <summary></summary>
  22. public event SocketEvent<string> OnMessage;
  23. /// <summary></summary>
  24. public event SocketEvent<byte[]> OnBytes;
  25. /// <summary></summary>
  26. public event SocketEvent<byte[]> OnPing;
  27. /// <summary></summary>
  28. public event SocketEvent<byte[]> OnPong;
  29. /// <summary></summary>
  30. public event SocketEvent<Exception> OnError;
  31. /// <summary></summary>
  32. public event ServerEvent<Exception> Excepted;
  33. #region Properties
  34. /// <summary>正在监听。</summary>
  35. public bool Running
  36. {
  37. get { return _running; }
  38. }
  39. /// <summary>监听的地址。</summary>
  40. public string Address
  41. {
  42. get { return _address; }
  43. }
  44. /// <summary>监听的端口号。</summary>
  45. public int Port
  46. {
  47. get { return _port; }
  48. }
  49. /// <summary>当前 Sockets 数量。</summary>
  50. public int Count
  51. {
  52. get
  53. {
  54. var count = 0;
  55. lock (_connections) { count = _connections.Count; }
  56. return count;
  57. }
  58. }
  59. #endregion
  60. #region Methods
  61. /// <summary></summary>
  62. public GenericServer() { }
  63. /// <summary>关闭服务,并释放系统资源。</summary>
  64. public void Dispose()
  65. {
  66. lock (_connections)
  67. {
  68. _connections.Clear();
  69. }
  70. lock (_server)
  71. {
  72. if (_server != null)
  73. {
  74. _server.Dispose();
  75. }
  76. }
  77. _server = null;
  78. _running = false;
  79. }
  80. /// <summary>启动监听,如果监听正在运行则失败。</summary>
  81. public bool Start(int port = DefaultPort, string address = DefaultAddress)
  82. {
  83. if (address == null) return false;
  84. if (_running) return false;
  85. _address = address ?? "";
  86. _port = NumberUtility.Restrict( port, 0, ushort.MaxValue);
  87. try
  88. {
  89. var location = "ws://" + address + ":" + port.ToString();
  90. _server = new WebSocketServer(location);
  91. _server.Start(Initialize);
  92. _running = true;
  93. return true;
  94. }
  95. catch (Exception exception)
  96. {
  97. RaiseExcepted(exception);
  98. return false;
  99. }
  100. }
  101. /// <summary>对所有连接发送文本。</summary>
  102. /// <exception cref="InvalidOperationException"></exception>
  103. public int Send(params char[] message)
  104. {
  105. var text = null as string;
  106. if (message == null || message.Length < 1) return 0;
  107. if (message.Length == 1)
  108. {
  109. text = message[0].ToString();
  110. }
  111. else
  112. {
  113. var sb = new System.Text.StringBuilder();
  114. foreach (var i in message)
  115. {
  116. if ((object)i != null) sb.Append(i);
  117. }
  118. text = sb.ToString();
  119. }
  120. if (text.Length < 1) return 0;
  121. var connections = GetConnections();
  122. var count = 0;
  123. foreach (var connection in connections)
  124. {
  125. try
  126. {
  127. var sent = connection.Send(message);
  128. if (sent != null) count += 1;
  129. }
  130. catch (Exception exception)
  131. {
  132. RaiseExcepted(exception);
  133. }
  134. }
  135. return count;
  136. }
  137. /// <summary>发送文本。</summary>
  138. /// <exception cref="InvalidOperationException"></exception>
  139. public int Send(params string[] message)
  140. {
  141. var text = null as string;
  142. if (message == null || message.Length < 1) return 0;
  143. if (message.Length == 1)
  144. {
  145. text = message[0].ToString();
  146. }
  147. else
  148. {
  149. var sb = new System.Text.StringBuilder();
  150. foreach (var i in message)
  151. {
  152. if (i != null) sb.Append(i);
  153. }
  154. text = sb.ToString();
  155. }
  156. if (text.Length < 1) return 0;
  157. var connections = GetConnections();
  158. var count = 0;
  159. foreach (var connection in connections)
  160. {
  161. try
  162. {
  163. var sent = connection.Send(message);
  164. if (sent != null) count += 1;
  165. }
  166. catch (Exception exception)
  167. {
  168. RaiseExcepted(exception);
  169. }
  170. }
  171. return count;
  172. }
  173. /// <summary>发送字节数组。</summary>
  174. /// <exception cref="InvalidOperationException"></exception>
  175. public int Send(params byte[] message)
  176. {
  177. var connections = GetConnections();
  178. var count = 0;
  179. foreach (var connection in connections)
  180. {
  181. try
  182. {
  183. var sent = connection.Send(message);
  184. if (sent != null) count += 1;
  185. }
  186. catch (Exception exception)
  187. {
  188. RaiseExcepted(exception);
  189. }
  190. }
  191. return count;
  192. }
  193. /// <summary>发送 PING。</summary>
  194. /// <exception cref="InvalidOperationException"></exception>
  195. public int Ping(params byte[] message)
  196. {
  197. var connections = GetConnections();
  198. var count = 0;
  199. foreach (var connection in connections)
  200. {
  201. try
  202. {
  203. var sent = connection.Ping(message);
  204. if (sent != null) count += 1;
  205. }
  206. catch (Exception exception)
  207. {
  208. RaiseExcepted(exception);
  209. }
  210. }
  211. return count;
  212. }
  213. /// <summary>发送 PONG。</summary>
  214. /// <exception cref="InvalidOperationException"></exception>
  215. public int Pong(params byte[] message)
  216. {
  217. var connections = GetConnections();
  218. var count = 0;
  219. foreach (var connection in connections)
  220. {
  221. try
  222. {
  223. var sent = connection.Pong(message);
  224. if (sent != null) count += 1;
  225. }
  226. catch (Exception exception)
  227. {
  228. RaiseExcepted(exception);
  229. }
  230. }
  231. return count;
  232. }
  233. /// <summary>关闭 Socket 连接。</summary>
  234. public void Close()
  235. {
  236. lock (_server)
  237. {
  238. try
  239. {
  240. if (_server != null && _server.ListenerSocket != null)
  241. {
  242. _server.ListenerSocket.Close();
  243. }
  244. }
  245. catch (Exception exception)
  246. {
  247. RaiseExcepted(exception);
  248. }
  249. }
  250. }
  251. #endregion
  252. #region Private
  253. List<Connection> GetConnections()
  254. {
  255. var list = new List<Connection>();
  256. lock (_connections)
  257. {
  258. foreach (var i in _connections.Values)
  259. {
  260. if (i != null) list.Add(i);
  261. }
  262. }
  263. return list;
  264. }
  265. void RaiseExcepted(Exception exception)
  266. {
  267. if (exception == null) return;
  268. if (Excepted == null) return;
  269. try
  270. {
  271. InBackground(() => Excepted(this, exception));
  272. }
  273. catch { }
  274. }
  275. void Initialize(Connection socket)
  276. {
  277. if (socket == null) return;
  278. socket.OnOpen = () => InBackground(() =>
  279. {
  280. var hashcode = socket.GetHashCode();
  281. lock (_connections)
  282. {
  283. if (!_connections.ContainsKey(hashcode))
  284. {
  285. _connections.Add(hashcode, socket);
  286. }
  287. }
  288. try
  289. {
  290. OnOpen?.Invoke(socket);
  291. }
  292. catch (Exception exception)
  293. {
  294. RaiseExcepted(exception);
  295. }
  296. });
  297. socket.OnClose = () => InBackground(() =>
  298. {
  299. var hashcode = socket.GetHashCode();
  300. try
  301. {
  302. OnClose?.Invoke(socket);
  303. }
  304. catch (Exception exception)
  305. {
  306. RaiseExcepted(exception);
  307. }
  308. });
  309. socket.OnBytes = (content) => InBackground(() =>
  310. {
  311. try
  312. {
  313. OnBytes?.Invoke(socket, content);
  314. }
  315. catch (Exception exception)
  316. {
  317. RaiseExcepted(exception);
  318. }
  319. });
  320. socket.OnError = (content) => InBackground(() =>
  321. {
  322. try
  323. {
  324. OnError?.Invoke(socket, content);
  325. }
  326. catch (Exception exception)
  327. {
  328. RaiseExcepted(exception);
  329. }
  330. });
  331. socket.OnMessage = (content) => InBackground(() =>
  332. {
  333. try
  334. {
  335. OnMessage?.Invoke(socket, content);
  336. }
  337. catch (Exception exception)
  338. {
  339. RaiseExcepted(exception);
  340. }
  341. });
  342. socket.OnPing = (content) => InBackground(() =>
  343. {
  344. try
  345. {
  346. if (OnPing == null) socket.Pong(content);
  347. else OnPing?.Invoke(socket, content);
  348. }
  349. catch (Exception exception)
  350. {
  351. RaiseExcepted(exception);
  352. }
  353. });
  354. socket.OnPong = (content) => InBackground(() =>
  355. {
  356. try
  357. {
  358. OnPong?.Invoke(socket, content);
  359. }
  360. catch (Exception exception)
  361. {
  362. RaiseExcepted(exception);
  363. }
  364. });
  365. }
  366. int GetHashCode(Connection connection)
  367. {
  368. if (connection == null) return 0;
  369. if (connection.ConnectionInfo == null) return 0;
  370. return connection.ConnectionInfo.Id.GetHashCode();
  371. }
  372. #endregion
  373. #region static
  374. /// <summary></summary>
  375. public static LogLevel LogLevel
  376. {
  377. get { return WebSocketLog.Level; }
  378. set { WebSocketLog.Level = value; }
  379. }
  380. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
  381. private static void InBackground(System.Action action)
  382. {
  383. if (action == null) return;
  384. var thread = new System.Threading.Thread(delegate (object v) { ((System.Action)v)(); });
  385. thread.IsBackground = true;
  386. thread.Start(action);
  387. }
  388. #endregion
  389. }
  390. }
  391. #endif