如何处理GUI程序中的socket监听器无限循环?
我正在创建一个简单的异步套接字侦听器,充当设备的网关。该侦听器将侦听任意端口,并为其他软件提供 API 以通过网络访问设备。
要创建异步套接字侦听器,基于 MSDN 上的这篇文章,我必须创建一个无限循环,如下所示:
while (true) {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener
);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
控制台程序原型运行良好。但是,我打算创建异步套接字侦听器的 GUI 版本。我知道如果我在 GUI 中执行无限循环,GUI 将挂起。如何为侦听器提供图形用户界面?我希望有一个不涉及线程的简单解决方案。
I'm creating a simple asynchronous socket listener that acts as a gateway to devices. This listener will listen to an arbitrary port and provides an API for other software to access devices over the network.
To create an asynchronous socket listener, based on this article on MSDN, I have to create an infinite loop, like this:
while (true) {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener
);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
The console program prototype runs well. However, I intend to create a GUI version of the asynchronous socket listener. I know that if I do the infinite loop in the GUI, the GUI will hang. How do I give a graphical user interface to the listener? I'm hoping for a simple solution that doesn't involve threads.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将循环放在单独的线程中。
或者使用上面代码的“异步”部分:创建套接字时调用
BeginAccept
,并在处理完成后在回调中再次执行此操作。这样你就根本不需要信号或循环。Either you can put the loop in a separate thread.
Or use the "asynch" part of the above code: When socket is created call
BeginAccept
, and in the callback do it again when done with processing. This way you don't need signals or loops at all.