在C#中实现套接字侦听器的最佳方法

前端之家收集整理的这篇文章主要介绍了在C#中实现套接字侦听器的最佳方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经找到了答案,但找不到类似的东西……

我对C#很新.我需要使用WinForms在C#中创建一个程序.它基本上有两个组件:UI然后我需要有一个永久侦听套接字TCP端口的进程.如果收到了任何内容,那么我需要提出一个类似的事件,以便我可以更新UI.

问题:在程序运行时,实现需要一直监听的进程的最佳方法是什么?

然后,当我收到消息时,如何通知UI它需要更新?

谢谢!

解决方法

您可以使用等待另一个线程上的传入连接的TcpListener.每次收到新连接时,都要创建一个新线程来处理它.使用Control.Invoke从非UI线程更新UI.这是一个简短的例子:
  1. public MainForm()
  2. {
  3. InitializeComponents();
  4. StartListener();
  5. }
  6.  
  7. private TcpListener _listener;
  8. private Thread _listenerThread;
  9.  
  10. private void StartListener()
  11. {
  12. _listenerThread = new Thread(RunListener);
  13. _listenerThread.Start();
  14. }
  15.  
  16. private void RunListener()
  17. {
  18. _listener = new TcpListener(IPAddress.Any,8080);
  19. _listener.Start();
  20. while(true)
  21. {
  22. TcpClient client = _listener.AcceptTcpClient();
  23. this.Invoke(
  24. new Action(
  25. () =>
  26. {
  27. textBoxLog.Text += string.Format("\nNew connection from {0}",client.Client.RemoteEndPoint);
  28. }
  29. ));;
  30. ThreadPool.QueueUserWorkItem(ProcessClient,client);
  31. }
  32. }
  33.  
  34. private void ProcessClient(object state)
  35. {
  36. TcpClient client = state as TcpClient;
  37. // Do something with client
  38. // ...
  39. }

猜你在找的C#相关文章