BasicClass.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = 0;
  56. if(Stream!=null)
  57. {
  58. len = Stream.Read(rd, index, rd.Length - index);
  59. }
  60. if (len == 0)
  61. return -1;//这里控制读取不到数据时就跳出,网络异常断开,数据读取不完整。
  62. else
  63. index += len;
  64. } while (index < rd.Length);
  65. return 0;
  66. }
  67. catch
  68. {
  69. return -1;
  70. }
  71. }
  72. }
  73. }