[英]C++ Windows Sockets - Close socket at program exit
I'm making a simple console client/server application with the WinSock2 api, but I need to make sure that the socket of the client closes properly when exiting the application. 我正在使用WinSock2 API创建一个简单的控制台客户端/服务器应用程序,但是我需要确保退出应用程序时客户端的套接字正确关闭。 I have already tried to use a
SetConsoleCtrlHandler
but that makes a thread where the main loop keeps running for 10 seconds. 我已经尝试过使用
SetConsoleCtrlHandler
但这会使主循环保持运行10秒钟的线程成为一个线程。
Is there a way to close the socket when the user pressed the close button? 用户按下关闭按钮时,是否可以关闭插座?
Yes, Wrap native Winsock2 socket with a class that manages it. 是的,用管理它的类包装本地Winsock2套接字。
class Socket{
SOCKET m_NativeSocket;
public:
Socket(){
m_NativeSocket = ::socket(...);
}
~Socket(){
::closesocket(m_NativeSocket);
}
};
You should follow this pattern because: 您应遵循此模式,因为:
make sure you implement proper move constructor. 确保实现正确的move构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.