You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 line
2.3 KiB

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