问题描述
限时送ChatGPT账号..我已经搜索了答案,但找不到任何类似的东西...
I did search for answers already, but can't find anything similar...
我对 C# 还很陌生.我需要使用 WinForms 在 C# 中创建一个程序.它基本上有 2 个组件:UI,然后我需要一个进程来永久侦听套接字 TCP 端口.如果收到任何信息,那么我需要引发一个事件或类似事件,以便我可以更新 UI.
I'm fairly new to C#. I need to create a program in C# using WinForms. It basically has 2 components: UI and then I need to have a process that permanently listens on a socket TCP port. If there's anything received, then I need to raise an event or something similar so I can update the UI.
问题:实现需要在程序运行时一直监听的进程的最佳方法是什么?
Question: what is the best way to implement a process that needs to be listening all the time while the program is running?
然后,当我收到消息时,如何通知 UI 需要更新?
And then, when I receive a message, how can I notify the UI that it needs to be updated?
谢谢!
推荐答案
您可以使用 TcpListener
等待另一个线程上的传入连接.每次收到新连接时,创建一个新线程来处理它.使用 Control.Invoke
从非 UI 线程更新 UI.这是一个简短的例子:
You can use a TcpListener
that waits for incoming connections on another thread. Every time you receive a new connection, create a new thread to process it. Use Control.Invoke
to update the UI from the non-UI thread. Here's a short example :
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
// ...
}
这篇关于在 C# 中实现套接字侦听器的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论