Server.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Collections;
  7. using System.Threading;
  8. using System.Net;
  9. using System.Data.SqlClient;
  10. using System.Configuration;
  11. using System.Windows.Forms;
  12. namespace AGV_WPF.Services
  13. {
  14. public class Server
  15. {
  16. public Server()
  17. {
  18. //clientTable = new Hashtable();
  19. try
  20. {
  21. using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))
  22. {
  23. con.Open();
  24. databaseStr = con.Database;
  25. con.Close();
  26. }
  27. }
  28. catch (System.Exception ex)
  29. {
  30. databaseStr = "Error";
  31. }
  32. }
  33. string databaseStr;
  34. private string localIP;
  35. public string LocalIP
  36. {
  37. get { return localIP; }
  38. set
  39. {
  40. if(localIP != value)
  41. localIP = value;
  42. }
  43. }
  44. private int port;
  45. public int Port
  46. {
  47. get { return port; }
  48. set
  49. {
  50. if(port != value)
  51. port = value;
  52. }
  53. }
  54. public TcpListener server = null;
  55. public Thread thread = null;
  56. public Thread receiveThread = null;
  57. public Thread sendThread = null;
  58. public static Hashtable clientTable = new Hashtable();
  59. public bool IsThreadActive = false;//监听线程是否活动状态
  60. public delegate void InvokeDelegate();
  61. public static event EventHandler ClientChanged;
  62. void ConnectHandler()
  63. {
  64. try
  65. {
  66. IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName());
  67. for (int i = 0; i < address.Count();i++ )
  68. {
  69. if (address[i].AddressFamily.ToString().ToLower()=="internetwork" && address[i].ToString() == LocalIP)
  70. {
  71. server = new TcpListener(IPAddress.Parse(LocalIP), Port);
  72. server.Start();
  73. break;
  74. }
  75. else if (i == address.Count() - 1)
  76. {
  77. MessageBox.Show("IP地址不存在");
  78. //throw new Exception("IP地址不存在");
  79. return;
  80. }
  81. }
  82. }
  83. catch (System.Exception ex)
  84. {
  85. //MessageBox.Show(ex.Message);
  86. throw new Exception(ex.Message);
  87. }
  88. while (IsThreadActive)
  89. {
  90. if (server.Pending())
  91. {
  92. TcpClient client = server.AcceptTcpClient();
  93. receiveThread = new Thread(ReceiveHandler);
  94. receiveThread.IsBackground = true;
  95. clientTable.Add(client, receiveThread);
  96. if (ClientChanged != null)
  97. {
  98. ClientChanged(clientTable, null);
  99. }
  100. receiveThread.Start(client);
  101. }
  102. else
  103. {
  104. Thread.Sleep(3000);//3秒扫描一次
  105. }
  106. }
  107. }
  108. void ReceiveHandler(object o)
  109. {
  110. TcpClient client = o as TcpClient;
  111. int i = 0;
  112. byte[] buffer = new byte[1024];
  113. while (true)
  114. {
  115. if (client.Client.Poll(-1, SelectMode.SelectRead))
  116. {
  117. try
  118. {
  119. i = client.Client.Receive(buffer);
  120. }
  121. catch (System.Net.Sockets.SocketException ex)
  122. {
  123. if (clientTable.ContainsKey(client))
  124. {
  125. client.Close();
  126. clientTable.Remove(client);
  127. if (ClientChanged != null)
  128. {
  129. ClientChanged(clientTable, null);
  130. }
  131. //MessageBox.Show("客户端强制下线");
  132. }
  133. break;
  134. }
  135. if (i == 0)
  136. {
  137. if (clientTable.ContainsKey(client))
  138. {
  139. client.Close();
  140. clientTable.Remove(client);
  141. if (ClientChanged != null)
  142. {
  143. ClientChanged(clientTable, null);
  144. }
  145. }
  146. break;
  147. }
  148. /*
  149. else if (i > 0)
  150. {
  151. string str = System.Text.Encoding.Default.GetString(buffer, 0, i);
  152. client.Client.Send(new byte[1]);
  153. }*/
  154. }
  155. }
  156. }
  157. void SendHandler()
  158. {
  159. byte[] buffer = System.Text.Encoding.Default.GetBytes(string.Format("#{0}#", databaseStr));
  160. while (true)
  161. {
  162. if (IsThreadActive)
  163. {
  164. foreach (DictionaryEntry dic in clientTable)
  165. {
  166. if (dic.Key != null)
  167. {
  168. TcpClient client = dic.Key as TcpClient;
  169. if (client != null)
  170. {
  171. try
  172. {
  173. client.Client.Send(buffer);
  174. }
  175. catch (System.Exception ex)
  176. {
  177. continue;
  178. }
  179. }
  180. }
  181. }
  182. }
  183. Thread.Sleep(3000);
  184. }
  185. }
  186. public void Open(string ip,int port)
  187. {
  188. if (thread != null && thread.ThreadState == ThreadState.Running)
  189. {
  190. //MessageBox.Show("正在监听中......");
  191. return;
  192. }
  193. try
  194. {
  195. this.LocalIP = ip;
  196. this.Port = port;
  197. thread = new Thread(new ThreadStart(ConnectHandler));
  198. thread.IsBackground = true;
  199. sendThread = new Thread(SendHandler);
  200. sendThread.IsBackground = true;
  201. IsThreadActive = true;
  202. thread.Start();
  203. sendThread.Start();
  204. }
  205. catch (System.Exception ex)
  206. {
  207. //MessageBox.Show(ex.Message);
  208. throw new Exception(ex.Message);
  209. //return;
  210. }
  211. }
  212. public void Close()
  213. {
  214. if (thread != null)
  215. {
  216. IsThreadActive = false;
  217. thread.Abort();
  218. }
  219. if (sendThread != null)
  220. {
  221. sendThread.Abort();
  222. }
  223. foreach (DictionaryEntry dic in clientTable)
  224. {
  225. if (dic.Value != null)
  226. {
  227. Thread t = dic.Value as Thread;
  228. if (t != null)
  229. {
  230. t.Abort();
  231. }
  232. }
  233. }
  234. if (server != null)
  235. server.Stop();
  236. clientTable.Clear();//移除所有客户信息
  237. }
  238. public static byte[] HexToByte(string msg)
  239. {
  240. msg = msg.Replace(" ", "");//移除空格
  241. if (msg.Length % 2 != 0)
  242. msg = msg.Substring(0, msg.Length - 1);
  243. byte[] comBuffer = new byte[msg.Length / 2];
  244. for (int i = 0; i < msg.Length; i += 2)
  245. {
  246. comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
  247. }
  248. return comBuffer;
  249. }
  250. }
  251. }