我已经找到了答案,但找不到类似的东西……
我对C#很新.我需要使用WinForms在C#中创建一个程序.它基本上有两个组件:UI然后我需要有一个永久侦听套接字TCP端口的进程.如果收到了任何内容,那么我需要提出一个类似的事件,以便我可以更新UI.
问题:在程序运行时,实现需要一直监听的进程的最佳方法是什么?
然后,当我收到消息时,如何通知UI它需要更新?
谢谢!
解决方法
您可以使用等待另一个线程上的传入连接的TcpListener.每次收到新连接时,都要创建一个新线程来处理它.使用Control.Invoke从非UI线程更新UI.这是一个简短的例子:
- public MainForm()
- {
- InitializeComponents();
- StartListener();
- }
- private TcpListener _listener;
- private Thread _listenerThread;
- private void StartListener()
- {
- _listenerThread = new Thread(RunListener);
- _listenerThread.Start();
- }
- private void RunListener()
- {
- _listener = new TcpListener(IPAddress.Any,8080);
- _listener.Start();
- while(true)
- {
- TcpClient client = _listener.AcceptTcpClient();
- this.Invoke(
- new Action(
- () =>
- {
- textBoxLog.Text += string.Format("\nNew connection from {0}",client.Client.RemoteEndPoint);
- }
- ));;
- ThreadPool.QueueUserWorkItem(ProcessClient,client);
- }
- }
- private void ProcessClient(object state)
- {
- TcpClient client = state as TcpClient;
- // Do something with client
- // ...
- }