简体   繁体   English

C ++ Windows套接字-在程序退出时关闭套接字

[英]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: 您应遵循此模式,因为:

  1. Sockets are suitable as objects, not just floating variables 套接字适合作为对象,而不仅仅是浮动变量
  2. Adding destructor makes sure that no matter if the application suddenly aborts, an exception is thrown, socket is out of scope - the socket closes properly 添加析构函数可确保无论应用程序是否突然中止,抛出异常,套接字超出范围-套接字都能正常关闭
  3. It's nicer and cleaner to work with sockets as objects. 将套接字作为对象使用会更好,更清洁。

make sure you implement proper move constructor. 确保实现正确的move构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM