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.

107 lines
2.9 KiB

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