0

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. I have already tried to use a SetConsoleCtrlHandler but that makes a thread where the main loop keeps running for 10 seconds.

Is there a way to close the socket when the user pressed the close button?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Appels
  • 23
  • 4
  • If you take no explicit action, and just close the app, does the socket not get closed by the OS process termination action? It does with my GUI apps. – Martin James Nov 14 '15 at 12:27
  • I just found out it actually did that already yes. Thanks for your help, but I am also implementing the object system as it is indeed cleaner to work with. (and thus, I am taking that as an 'accepted' answer). – Appels Nov 14 '15 at 13:23
  • You should look into [this question about RAII](http://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) – Rob K Mar 17 '16 at 19:30

1 Answers1

1

Yes, Wrap native Winsock2 socket with a class that manages it.

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.

David Haim
  • 25,446
  • 3
  • 44
  • 78