SocketTool.cs 6.2 KB

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