您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

119 行
3.0 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using StuMgmLib.MyNameSpace;
  7. namespace StuMgmClient
  8. {
  9. class SystemComm
  10. {
  11. #region 基本函数
  12. const int bufSize = 65535;
  13. static IPEndPoint m_ipEndpoint;
  14. static Socket m_socket;
  15. static byte[] m_buf;
  16. internal static void Init(string ip, int port)
  17. {
  18. IPAddress ipAdress = IPAddress.Parse(ip);
  19. m_ipEndpoint = new IPEndPoint(ipAdress, port);
  20. m_buf = new byte[bufSize];
  21. }
  22. static bool Connect()
  23. {
  24. try
  25. {
  26. m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  27. m_socket.Connect(m_ipEndpoint);
  28. return m_socket.Connected;
  29. }
  30. catch (Exception ex)
  31. {
  32. Debug.Print(ex.Message);
  33. return false;
  34. }
  35. }
  36. static bool Send(byte[] data)
  37. {
  38. try
  39. {
  40. m_socket.Send(data);
  41. return true;
  42. }
  43. catch(Exception e)
  44. {
  45. Debug.Print(e.Message);
  46. return false;
  47. }
  48. }
  49. static bool Receive()
  50. {
  51. try
  52. {
  53. Array.Clear(m_buf, 0, m_buf.Length);
  54. m_socket.Receive(m_buf);
  55. return true;
  56. }
  57. catch (Exception e)
  58. {
  59. Debug.Print(e.Message);
  60. return false;
  61. }
  62. }
  63. static void DisConnect()
  64. {
  65. m_socket.Close();
  66. }
  67. #endregion
  68. internal static ErrCode GetData(ClientRequest req,out ServerResponse o)
  69. {
  70. o = null;
  71. if (!Connect())
  72. return ErrCode.FailConnect;
  73. byte[] sendBuf;
  74. if (!Utility.BinSerialize(req, out sendBuf))
  75. return ErrCode.FailSerial;
  76. if (!Send(sendBuf))
  77. return ErrCode.FailSend;
  78. if (!Receive())
  79. return ErrCode.FailReceive;
  80. DisConnect();
  81. if (!Utility.BinDeserialize(m_buf, out o))
  82. return ErrCode.FailDeserial;
  83. return ErrCode.Success;
  84. }
  85. internal static ErrCode sendData(ClientRequest req,out ServerResponse o)
  86. {
  87. o = null;
  88. if (!Connect())
  89. return ErrCode.FailConnect;
  90. byte[] sendBuf;
  91. if (!Utility.BinSerialize(req, out sendBuf))
  92. return ErrCode.FailSerial;
  93. if (!Send(sendBuf))
  94. return ErrCode.FailSend;
  95. if (!Receive())
  96. return ErrCode.FailReceive;
  97. DisConnect();
  98. if (!Utility.BinDeserialize(m_buf, out o))
  99. return ErrCode.FailDeserial;
  100. return ErrCode.Success;
  101. }
  102. }
  103. }