SocketTool.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Azylee.YeahWeb.SocketUtils
  9. {
  10. public class SocketTool : IDisposable
  11. {
  12. const int ReceiveBufferSize = 1024;
  13. private string _IP;
  14. private int _Port;
  15. private bool IsReceive = false;
  16. private List<byte> ReceiveByte = new List<byte>();
  17. private readonly object ReceiveLock = new object();
  18. public string IP { get; }
  19. public int Port { get; }
  20. private IPAddress IPAddress { get; set; }
  21. private IPEndPoint IPEndPoint { get; set; }
  22. public Socket Socket { get; set; }
  23. public delegate void GetByteDelegate(byte[] b);
  24. public GetByteDelegate ReceiveByteContent;
  25. private SocketTool() { }
  26. public SocketTool(string ip, int port)
  27. {
  28. _IP = ip;
  29. _Port = port;
  30. IPAddress = IPAddress.Parse(ip);
  31. IPEndPoint = new IPEndPoint(IPAddress, port);
  32. }
  33. public bool Connect()
  34. {
  35. try
  36. {
  37. if (Socket != null)
  38. {
  39. return true;
  40. }
  41. else
  42. {
  43. Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  44. Socket.Connect(IPEndPoint);
  45. return true;
  46. }
  47. }
  48. catch { }
  49. return false;
  50. }
  51. public bool Send(string s)
  52. {
  53. try
  54. {
  55. byte[] sb = Encoding.ASCII.GetBytes(s);
  56. return Send(sb);
  57. }
  58. catch { }
  59. return false;
  60. }
  61. public bool Send(byte[] b)
  62. {
  63. try
  64. {
  65. int rs = Socket.Send(b);
  66. if (rs > 0) return true;
  67. }
  68. catch { }
  69. return false;
  70. }
  71. public void Receive()
  72. {
  73. Task.Factory.StartNew(() =>
  74. {
  75. if (!IsReceive)
  76. {
  77. lock (ReceiveLock)
  78. {
  79. if (!IsReceive)
  80. {
  81. IsReceive = true;
  82. while (IsReceive)
  83. {
  84. ReceiveContent();
  85. }
  86. }
  87. }
  88. }
  89. });
  90. }
  91. private void ReceiveContent()
  92. {
  93. //string recStr = "";
  94. //byte[] recBytes = new byte[4096];
  95. //int bytes = Socket.Receive(recBytes, recBytes.Length, 0);
  96. //recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
  97. try
  98. {
  99. byte[] recByte = new byte[ReceiveBufferSize];
  100. int recLength = Socket.Receive(recByte, recByte.Length, 0);
  101. for (int k = 0; k < recLength; k++)
  102. {
  103. ReceiveByte.Add(recByte[k]);
  104. }
  105. if (ReceiveByte.Count > 6 && ReceiveByte[0] == 255 && ReceiveByte[1] == 254)
  106. {
  107. int msgBodyLength = BitConverter.ToInt32(new byte[] { ReceiveByte[2], ReceiveByte[3], ReceiveByte[4], ReceiveByte[5] }, 0);
  108. if (ReceiveByte.Count >= 6 + msgBodyLength)
  109. {
  110. byte[] body = ReceiveByte.GetRange(6, msgBodyLength).ToArray();
  111. string bodyToGBK = Encoding.GetEncoding("GBK").GetString(body);
  112. ReceiveByteContent(body);
  113. Send(ReceiveByte.GetRange(0, 6).ToArray());
  114. ReceiveByte.RemoveRange(0, 6 + msgBodyLength);
  115. }
  116. }
  117. else
  118. {
  119. ReceiveByte.Clear();
  120. Socket.Send(new byte[] { 0 });
  121. }
  122. //string recStr = Encoding.GetEncoding("GBK").GetString(recByte, 0, recLength);
  123. //if (recLength > 0)
  124. //{
  125. // Console.Write("rec:");
  126. // for (int j = 0; j < recLength; j++)
  127. // {
  128. // Console.Write(recByte[j] + " ");
  129. // }
  130. // Console.WriteLine(" ,");
  131. //}
  132. //if (recStr.Length > 0)
  133. // Console.WriteLine("接收到信息:" + recStr);
  134. }
  135. catch (Exception e)
  136. { }
  137. }
  138. #region IDisposable Support
  139. private bool disposedValue = false; // 要检测冗余调用
  140. protected virtual void Dispose(bool disposing)
  141. {
  142. if (!disposedValue)
  143. {
  144. if (disposing)
  145. {
  146. // TODO: 释放托管状态(托管对象)。
  147. IsReceive = false;
  148. Socket?.Shutdown(SocketShutdown.Both);
  149. Socket?.Close();
  150. Socket?.Dispose();
  151. }
  152. // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
  153. // TODO: 将大型字段设置为 null。
  154. disposedValue = true;
  155. }
  156. }
  157. // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
  158. // ~SocketTool() {
  159. // // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
  160. // Dispose(false);
  161. // }
  162. // 添加此代码以正确实现可处置模式。
  163. public void Dispose()
  164. {
  165. // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
  166. Dispose(true);
  167. // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
  168. // GC.SuppressFinalize(this);
  169. }
  170. #endregion
  171. }
  172. }