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.

91 lines
2.4 KiB

  1. using System;
  2. using System.Threading;
  3. using System.Windows.Forms;
  4. using StuMgmLib.MyNameSpace;
  5. namespace Test
  6. {
  7. public partial class Form1 : Form
  8. {
  9. TcpConn tcpConn = new TcpConn();
  10. Thread tUpdateUi = null;
  11. private delegate void SetTextCallback(string text);
  12. public Form1()
  13. {
  14. InitializeComponent();
  15. }
  16. private void Server_FormClosed(object sender, FormClosedEventArgs e)
  17. {
  18. System.Environment.Exit(0);
  19. }
  20. /// <summary>
  21. /// 委托:更新界面方法
  22. /// </summary>
  23. private void setText(string text)
  24. {
  25. if (rtxHistory.InvokeRequired)
  26. {
  27. SetTextCallback method = new SetTextCallback(setText);
  28. Invoke(method, new object[] { text });
  29. }
  30. else
  31. {
  32. rtxHistory.Text = text + rtxHistory.Text;
  33. }
  34. }
  35. /// <summary>
  36. /// btn开关点击事件:开启、关闭服务器
  37. /// </summary>
  38. private void btnSerSwitch_Click(object sender, EventArgs e)
  39. {
  40. bool sFlag = tcpConn.SocketExist;
  41. try
  42. {
  43. if (sFlag == true)
  44. tcpConn.CloseServer();
  45. else if (sFlag != true)
  46. {
  47. int port = Convert.ToInt16(txtPort.Text);
  48. tcpConn.OpenServer(port);
  49. tUpdateUi = new Thread(updateHistory);
  50. tUpdateUi.Start();
  51. }
  52. }
  53. catch (Exception ep)
  54. {
  55. MessageBox.Show(ep.Message);
  56. }
  57. }
  58. /// <summary>
  59. /// 线程:接收客户端连接,接收数据,数据处理;更新历史界面
  60. /// </summary>
  61. private void updateHistory()
  62. {
  63. while (tcpConn.SocketExist)
  64. {
  65. setText(tcpConn.acceptConnection());
  66. setText(tcpConn.acpMsg());
  67. }
  68. }
  69. /// <summary>
  70. /// 定时器更新btn开关服务器
  71. /// </summary>
  72. private void tmr_Tick(object sender, EventArgs e)
  73. {
  74. if (tcpConn.SocketExist)
  75. btnSerSwitch.Text = "关闭服务器";
  76. else
  77. btnSerSwitch.Text = "开启服务器";
  78. }
  79. }
  80. }