Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

111 rader
3.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. namespace StuMgmLib.MyNameSpace
  7. {
  8. // 还有一种验证连接方式 Token
  9. public class TcpConn
  10. {
  11. private IPEndPoint IPP = null;
  12. private Socket socket = null;
  13. private Socket socketClient = null;
  14. private bool my_SocketExist = false;
  15. /// <summary>
  16. /// 判断服务器开关
  17. /// </summary>
  18. public bool SocketExist
  19. {
  20. get { return my_SocketExist; }
  21. private set { my_SocketExist = value; }
  22. }
  23. #region 开启服务器
  24. public void OpenServer(int port)
  25. {
  26. IPP = new IPEndPoint(IPAddress.Parse("10.10.0.44"), port);
  27. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  28. socket.Bind(IPP);
  29. socket.Listen(0);
  30. SocketExist = true;
  31. }
  32. #endregion
  33. #region 关闭服务器
  34. public void CloseServer()
  35. {
  36. if (socketClient != null)
  37. socketClient.Close();
  38. if (socket != null)
  39. socket.Close();
  40. SocketExist = false;
  41. }
  42. #endregion
  43. #region 接收客户端连接
  44. /// <summary>
  45. /// 接收客户端连接
  46. /// </summary>
  47. public string AcceptConn()
  48. {
  49. try
  50. {
  51. socketClient = socket.Accept(); // 阻塞等待客户端连接
  52. return socketClient.RemoteEndPoint.ToString() + " 已连接 \n";
  53. }
  54. catch (Exception)
  55. {
  56. return null;
  57. }
  58. }
  59. #endregion
  60. const int recvTimeOut = 3000; // 设置接收超时时间
  61. const int recvLength = 65535;
  62. #region 接收数据
  63. /// <summary>
  64. /// 接收数据
  65. /// </summary>
  66. public string AcpMsg()
  67. {
  68. byte[] dataRecv = new byte[recvLength]; // 定义接收数组
  69. string reEdPoint = "";
  70. try
  71. {
  72. reEdPoint = socketClient.RemoteEndPoint.ToString();
  73. socketClient.ReceiveTimeout = recvTimeOut;
  74. socketClient.Receive(dataRecv);
  75. var cs = BinaryED.Deserialize<Info.ClientSend>(dataRecv);
  76. Info.ServerSend ss = DataAnalyze.ClientSendAnalyze(cs);
  77. byte[] dataSend = BinaryED.Serialize<Info.ServerSend>(ss);
  78. socketClient.Send(dataSend);
  79. return reEdPoint + " 断开连接 \n";
  80. }
  81. catch // 客户端断开连接
  82. {
  83. if (socketClient != null)
  84. return reEdPoint + " 断开连接 \n";
  85. else
  86. return null;
  87. }
  88. finally
  89. {
  90. if (socketClient != null)
  91. socketClient.Close();
  92. }
  93. }
  94. #endregion
  95. }
  96. }