Close.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using SuperSocket.SocketBase;
  6. using SuperSocket.SocketBase.Command;
  7. using SuperWebSocket.Protocol;
  8. namespace SuperWebSocket.Command
  9. {
  10. /// <summary>
  11. /// The command handling close fragment
  12. /// </summary>
  13. /// <typeparam name="TWebSocketSession">The type of the web socket session.</typeparam>
  14. class Close<TWebSocketSession> : FragmentCommand<TWebSocketSession>
  15. where TWebSocketSession : WebSocketSession<TWebSocketSession>, new()
  16. {
  17. /// <summary>
  18. /// Gets the name.
  19. /// </summary>
  20. public override string Name
  21. {
  22. get
  23. {
  24. return OpCode.CloseTag;
  25. }
  26. }
  27. /// <summary>
  28. /// Executes the command.
  29. /// </summary>
  30. /// <param name="session">The session.</param>
  31. /// <param name="requestInfo">The request info.</param>
  32. public override void ExecuteCommand(TWebSocketSession session, IWebSocketFragment requestInfo)
  33. {
  34. var frame = requestInfo as WebSocketDataFrame;
  35. if (!CheckControlFrame(frame))
  36. {
  37. session.Close();
  38. return;
  39. }
  40. //the close handshake started from server side, now received a handshake response
  41. if (session.InClosing)
  42. {
  43. //Close the underlying socket directly
  44. session.Close(CloseReason.ClientClosing);
  45. return;
  46. }
  47. var data = GetWebSocketData(frame);
  48. var closeStatusCode = session.ProtocolProcessor.CloseStatusClode.NormalClosure;
  49. //var reasonText = string.Empty;
  50. if (data != null && data.Length > 0)
  51. {
  52. if (data.Length == 1)
  53. {
  54. session.Close(CloseReason.ProtocolError);
  55. return;
  56. }
  57. else
  58. {
  59. var code = data[0] * 256 + data[1];
  60. if (!session.ProtocolProcessor.IsValidCloseCode(code))
  61. {
  62. session.Close(CloseReason.ProtocolError);
  63. return;
  64. }
  65. closeStatusCode = code;
  66. //if (data.Length > 2)
  67. //{
  68. // reasonText = this.Utf8Encoding.GetString(data, 2, data.Length - 2);
  69. //}
  70. }
  71. }
  72. //Send handshake response
  73. session.SendCloseHandshakeResponse(closeStatusCode);
  74. //Don't include close reason the close handshake response for now
  75. //session.SendCloseHandshakeResponse(closeStatusCode, reasonText);
  76. //After both sending and receiving a Close message, the server MUST close the underlying TCP connection immediately
  77. session.Close(CloseReason.ClientClosing);
  78. }
  79. }
  80. }