BasicClass.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net.NetworkInformation;
  7. namespace OmronFinsTCP.Net
  8. {
  9. class BasicClass
  10. {
  11. internal static TcpClient Client;
  12. internal static NetworkStream Stream;
  13. internal static byte pcNode, plcNode;
  14. //检查PLC链接状况
  15. internal static bool PingCheck(string ip,int timeOut)
  16. {
  17. Ping ping = new Ping();
  18. PingReply pr = ping.Send(ip, timeOut);
  19. if (pr.Status == IPStatus.Success)
  20. return true;
  21. else
  22. return false;
  23. }
  24. //内部方法,发送数据
  25. internal static short SendData(byte[] sd)
  26. {
  27. try
  28. {
  29. Stream.Write(sd, 0, sd.Length);
  30. return 0;
  31. }
  32. catch
  33. {
  34. return -1;
  35. }
  36. }
  37. //内部方法,接收数据
  38. internal static short ReceiveData(byte[] rd)
  39. {
  40. try
  41. {
  42. //等待可读数据到底指定的长度,自己想的方法,下面的另一写法参考网络。
  43. //突然发现,此方法在数据量达不到指定长度时会死循环!
  44. //while (true)
  45. //{
  46. // Thread.Sleep(1);
  47. // if (Client.Available >= rd.Length && Stream.DataAvailable)
  48. // break;
  49. //}
  50. //this.Stream.Read(rd, 0, rd.Length);
  51. //另一写法:
  52. int index = 0;
  53. do
  54. {
  55. int len = Stream.Read(rd, index, rd.Length - index);
  56. if (len == 0)
  57. return -1;//这里控制读取不到数据时就跳出,网络异常断开,数据读取不完整。
  58. else
  59. index += len;
  60. } while (index < rd.Length);
  61. return 0;
  62. }
  63. catch
  64. {
  65. return -1;
  66. }
  67. }
  68. }
  69. }