Communicate.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using System;
  2. using System.Runtime.Serialization.Formatters.Binary;
  3. using System.IO;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. namespace CommonLib
  10. {
  11. public class Communicate
  12. {
  13. private Socket mySocket;
  14. private IPEndPoint myIPEndPoint;
  15. private byte[] tempByte = new byte[8];
  16. private string receiveMess;
  17. private NetPara _netPara;
  18. public bool FormOpening = false;
  19. public NetPara CommunicatePara
  20. {
  21. get { return this._netPara; }
  22. }
  23. public string ReadMess
  24. {
  25. get
  26. {
  27. if (receiveMess != null)
  28. {
  29. return this.receiveMess;
  30. }
  31. else
  32. return "0000000";
  33. }
  34. }
  35. public string NetName
  36. {
  37. set;
  38. get;
  39. }
  40. private bool conResult = false;
  41. public delegate void ConnectResultEventHandler(object sender, ResultEventArgs e);
  42. public delegate void MessageReceivedEventHandler(object sender, MessageEventArgs e);
  43. public event MessageReceivedEventHandler MessageReceived;//接受到数据事件
  44. public event ConnectResultEventHandler ConnectedResult;//连接成功事件
  45. public Communicate(string commName,string ip,int port )
  46. {
  47. try
  48. {
  49. this.NetName = commName;
  50. this._netPara = new NetPara(commName);
  51. this.myIPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
  52. mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  53. }
  54. catch (Exception ex)
  55. {
  56. System.Windows.Forms.MessageBox.Show("ERROR IP,Please reset." + ex.Message + ";" + ex.StackTrace);
  57. }
  58. System.Threading.Thread connectThread = new System.Threading.Thread(Connect);
  59. connectThread.IsBackground = true;
  60. connectThread.Start();
  61. System.Threading.Thread receiveThread = new System.Threading.Thread(ReceiveMessage);
  62. receiveThread.IsBackground = true;
  63. receiveThread.Start();
  64. }
  65. public class ResultEventArgs : EventArgs
  66. {
  67. public readonly bool conResult;
  68. public ResultEventArgs(bool conResult)
  69. {
  70. this.conResult = conResult;
  71. }
  72. }
  73. public class MessageEventArgs : EventArgs
  74. {
  75. public readonly string Message;
  76. public readonly byte[] byteMes;
  77. public MessageEventArgs(string Message, byte[] byteMes)
  78. {
  79. this.Message = Message;
  80. this.byteMes = byteMes;
  81. }
  82. //public MessageEventArgs(byte[] byteMes)
  83. //{
  84. // this.byteMes = byteMes;
  85. //}
  86. }
  87. public string IpAddress//定义属性--IP地址
  88. {
  89. set
  90. {
  91. this.myIPEndPoint.Address = IPAddress.Parse(value);
  92. }
  93. get
  94. {
  95. return this.myIPEndPoint.Address.ToString();
  96. }
  97. }
  98. public int Port//定义属性--端口号
  99. {
  100. set
  101. {
  102. this.myIPEndPoint.Port = value;
  103. }
  104. get
  105. {
  106. return myIPEndPoint.Port;
  107. }
  108. }
  109. int numberOfException = 0;
  110. public void Connect()//尝试连接服务器或者客户端
  111. {
  112. while (true)
  113. {
  114. if (CommunicatePara.客户端Or服务器 == NetBehavior.Client)
  115. {
  116. try
  117. {
  118. System.Threading.Thread.Sleep(300);
  119. mySocket.Connect(myIPEndPoint);
  120. conResult = true;
  121. ResultEventArgs e = new ResultEventArgs(conResult);
  122. ResultToDo(e);
  123. receiveMess = "";
  124. break;
  125. }
  126. catch
  127. {
  128. conResult = false;
  129. ResultEventArgs e = new ResultEventArgs(conResult);
  130. ResultToDo(e);
  131. }
  132. }
  133. else
  134. {
  135. System.Threading.Thread.Sleep(500);
  136. try
  137. {
  138. this.mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  139. myIPEndPoint.Address = IPAddress.Parse(this.IpAddress);
  140. mySocket.Bind(myIPEndPoint);
  141. mySocket.Listen(1);
  142. mySocket = mySocket.Accept();
  143. conResult = true;
  144. ResultEventArgs e = new ResultEventArgs(conResult);
  145. ResultToDo(e);
  146. }
  147. catch (Exception ex)
  148. {
  149. if ((ex is System.Net.Sockets.SocketException) && (numberOfException < 4))
  150. {
  151. if (mySocket.IsBound)
  152. {
  153. EndPoint edp = mySocket.RemoteEndPoint;
  154. mySocket.Shutdown(SocketShutdown.Both);
  155. mySocket.Close(100);
  156. Connect();
  157. numberOfException++;
  158. }
  159. }
  160. else
  161. {
  162. System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!\n" + ex.ToString());
  163. }
  164. }
  165. return;
  166. }
  167. }
  168. }
  169. public void closeSocket()
  170. {
  171. if (!FormOpening)
  172. {
  173. if (this.mySocket.Connected)
  174. {
  175. this.mySocket.Shutdown(SocketShutdown.Both);
  176. }
  177. if (this.mySocket != null)
  178. {
  179. this.mySocket.Close(100);
  180. this.mySocket = null;
  181. }
  182. }
  183. }
  184. protected virtual void ResultToDo(ResultEventArgs e)
  185. {
  186. if (ConnectedResult != null)
  187. {
  188. ConnectedResult(this, e);
  189. }
  190. }
  191. int headSize = 8;//包头长度 固定8
  192. byte StopByte = 0x00;
  193. int totalLen;
  194. int bodySize;
  195. int MID;
  196. byte[] surplusBuffer = null;//完整的数据包
  197. byte[] recvByte = null;//待发送的字节
  198. public void ReceiveMessage()//接收数据
  199. {
  200. while (FormOpening)
  201. {
  202. System.Threading.Thread.Sleep(20);
  203. if (mySocket != null)
  204. {
  205. if (mySocket.Connected)
  206. {
  207. int numReceive = 0;
  208. try
  209. {
  210. if (surplusBuffer == null)
  211. {
  212. numReceive = mySocket.Receive(tempByte, SocketFlags.None);
  213. }
  214. else
  215. {
  216. numReceive = mySocket.Receive(surplusBuffer, SocketFlags.None);
  217. }
  218. if (numReceive == 0)
  219. {
  220. byte[] temp = Encoding.Default.GetBytes(" ");
  221. mySocket.Send(temp);
  222. }
  223. }
  224. catch
  225. {
  226. if (this.mySocket != null)
  227. {
  228. conResult = false;
  229. ResultEventArgs e = new ResultEventArgs(conResult);
  230. ResultToDo(e);
  231. if (this.mySocket.Connected)
  232. {
  233. this.mySocket.Shutdown(SocketShutdown.Both);
  234. }
  235. this.mySocket.Close();
  236. this.mySocket = null;
  237. GC.Collect();
  238. this.mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  239. System.Threading.Thread connectThread = new System.Threading.Thread(Connect);
  240. connectThread.IsBackground = true;
  241. connectThread.Priority = System.Threading.ThreadPriority.Normal;
  242. connectThread.Start();
  243. }
  244. }
  245. if (numReceive > 0)
  246. {
  247. if (numReceive == 1)
  248. continue;
  249. if (surplusBuffer == null)//判断是不是第一次接收,为空则是第一次
  250. {
  251. if (tempByte[0].Equals(0x00))
  252. {
  253. bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 1, 4));//从包头里面分析出包体长度
  254. surplusBuffer = new byte[bodySize - headSize + 1];
  255. recvByte = new byte[headSize - 1];
  256. Buffer.BlockCopy(tempByte, 1, recvByte, 0, headSize - 1);
  257. }
  258. else
  259. {
  260. bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 0, 4));//从包头里面分析出包体长度
  261. surplusBuffer = new byte[bodySize - headSize];
  262. recvByte = tempByte;
  263. }
  264. //try
  265. //{
  266. // bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 0, 4));//从包头里面分析出包体长度
  267. // surplusBuffer = new byte[bodySize - headSize];
  268. // recvByte = tempByte;
  269. //}
  270. // catch
  271. //{
  272. // bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 1, 4));//从包头里面分析出包体长度
  273. // surplusBuffer = new byte[bodySize - headSize+1];
  274. // recvByte = new byte[bodySize];
  275. // Buffer.BlockCopy(tempByte, 1, recvByte, 0, headSize - 1);
  276. //}
  277. // }
  278. }
  279. else
  280. {
  281. // String receiveMess = bodySize.ToString("0000") + MID.ToString("0000") + Encoding.ASCII.GetString(surplusBuffer, 0, bodySize - headSize);
  282. recvByte = recvByte.Concat(surplusBuffer).ToArray();
  283. MessageEventArgs e = new MessageEventArgs(receiveMess, recvByte);
  284. if (MessageReceived != null)
  285. {
  286. MessageReceived(this, e);
  287. }
  288. surplusBuffer = null;//设置空 回到原始状态
  289. recvByte = null;
  290. totalLen = 0;//清0
  291. bodySize = 0;
  292. MID = 0;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }
  299. public void SendMessage(string s)//发送数据
  300. {
  301. if (FormOpening)
  302. {
  303. if (mySocket != null)
  304. {
  305. if (mySocket.Connected)
  306. {
  307. byte[] buffer = Encoding.Default.GetBytes(s);
  308. try
  309. {
  310. mySocket.Send(buffer, buffer.Length, SocketFlags.None);
  311. }
  312. catch
  313. {
  314. System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!");
  315. }
  316. }
  317. else
  318. {
  319. if (mySocket.Connected)
  320. {
  321. byte[] buffer = Encoding.Default.GetBytes(s);
  322. try
  323. {
  324. mySocket.Send(buffer, buffer.Length, SocketFlags.None);
  325. }
  326. catch
  327. {
  328. System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!");
  329. }
  330. }
  331. else
  332. {
  333. if (mySocket.Connected)
  334. {
  335. byte[] buffer = Encoding.Default.GetBytes(s);
  336. try
  337. {
  338. mySocket.Send(buffer, buffer.Length, SocketFlags.None);
  339. }
  340. catch
  341. {
  342. System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!");
  343. }
  344. }
  345. else
  346. {
  347. System.Windows.Forms.MessageBox.Show("网络未连接!");
  348. }
  349. }
  350. }
  351. }
  352. }
  353. }
  354. ////public System.Windows.Forms.DialogResult SetPara()
  355. ////{
  356. //// return new frmTcpIpConfig(this).ShowDialog();
  357. ////}
  358. }
  359. [Serializable]
  360. public enum NetBehavior
  361. {
  362. Server = 1, Client = 2
  363. }
  364. [Serializable]
  365. public class NetPara
  366. {
  367. private string _ip = "192.168.0.16";
  368. private int _port = 8080;
  369. private NetBehavior _behavior = NetBehavior.Client;
  370. private string _netParaName = System.Windows.Forms.Application.StartupPath + "\\dn.np";
  371. public string Ip
  372. {
  373. get { return _ip; }
  374. set { _ip = value; }
  375. }
  376. public int Port
  377. {
  378. get { return _port; }
  379. set { _port = value; }
  380. }
  381. public NetBehavior 客户端Or服务器
  382. {
  383. set
  384. {
  385. this._behavior = value;
  386. }
  387. get
  388. {
  389. return this._behavior;
  390. }
  391. }
  392. public string NetParaName
  393. {
  394. private set
  395. {
  396. this._netParaName = value;
  397. }
  398. get
  399. {
  400. return this._netParaName;
  401. }
  402. }
  403. public void SetPara(string ip, int port, NetBehavior 客户端Or服务器)
  404. {
  405. try
  406. {
  407. this._ip = ip;
  408. this._port = port;
  409. this._behavior = 客户端Or服务器;
  410. }
  411. catch (Exception ex)
  412. {
  413. System.Windows.Forms.MessageBox.Show("ERROR\r\n" + ex.Message, "Set param...");
  414. }
  415. }
  416. public void SavePara()
  417. {
  418. try
  419. {
  420. BinaryFormatter bf = new BinaryFormatter();
  421. FileStream fs = new FileStream(_netParaName, FileMode.OpenOrCreate, FileAccess.Write);
  422. bf.Serialize(fs, this);
  423. fs.Flush();
  424. fs.Close();
  425. //System.Windows.Forms.MessageBox.Show("用户数据保存成功!", "用户保存...");
  426. }
  427. catch (Exception ex)
  428. {
  429. System.Windows.Forms.MessageBox.Show("Save fail!\r\n " + ex.Message, "Save param......");
  430. }
  431. }
  432. public void IniPara()
  433. {
  434. //if (System.IO.File.Exists(_netParaName))
  435. {
  436. try
  437. {
  438. //BinaryFormatter bf = new BinaryFormatter();
  439. //FileStream fs = new FileStream(_netParaName, FileMode.Open, FileAccess.Read);
  440. //NetPara netPara = (NetPara)bf.Deserialize(fs);
  441. //fs.Flush();
  442. //fs.Close();
  443. //this.Ip = netPara.Ip;
  444. //this.Port = netPara.Port;
  445. this.客户端Or服务器 = NetBehavior.Client;
  446. //this.NetParaName = netPara.NetParaName;
  447. }
  448. catch (Exception ex)
  449. {
  450. System.Windows.Forms.MessageBox.Show("Init Fail!\r\n" + ex.Message, "Init...");
  451. }
  452. }
  453. }
  454. public NetPara(string paraName)
  455. {
  456. this._netParaName = string.Format("{0}\\{1}.np", System.Windows.Forms.Application.StartupPath, paraName);
  457. IniPara();
  458. }
  459. }
  460. }