gpt4 book ai didi

c++ - CSocket如何停止监听

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:00:35 24 4
gpt4 key购买 nike

所以,我有一个 CSocket 在工作线程中监听,它会执行阻塞接受,然后为每个新连接旋转另一个线程(是的,我知道性能不是问题)。

一个人应该如何停止倾听?您不能从另一个线程调用它关闭,因为 CSocket 将生成一个断言。

任何快速修复或只是扔掉这个设计糟糕的糟糕包装?

最佳答案

来自 MSDN:

If you want to handle this connection in a different thread, just passing the MFC object to the thread will not work correctly. To correctly set up everything for the connection to be handled in a different thread, the following steps are required:

  1. Detach the socket handle from the CAsyncSocket object in the thread where the connection was accepted.
  2. Pass the socket handle to the thread.
  3. In the thread, attach this handle to a CAsyncSocket derived object.

如果您正在创建性能关键程序,我个人会使用 IOCP .

代码将类似于:

Accept(ClientSocketObject, ... );
SOCKET s = ClientSocketObject.Detach();
CreateThread( ... ,(LPVOID)s, ...);

在你的线程程序中,

ThreadProc( SOCKET s ){
CAsyncSocket clientSocket;
clientSocket.Attach( s );

关于c++ - CSocket如何停止监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8154193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com