I'm trying to implement a simple TCP server application using winsock2. To this end I have a class that accepts connections (TcpServer
) and a class that handles connections (TcpListener
). To this end these objects need to share SOCKET
, whis is defined as UINT_PTR
. To safely share this a shared_ptr
seems to be the way to go. Unfortunately it seems that a shared_ptr
should wrap a struct
or class
, hence my implementation below.
struct SafeSocket_
{
SOCKET Socket;
SafeSocket_(SOCKET socket)
: Socket(socket)
{}
~SafeSocket_()
{
closesocket(Socket);
std::cout << "destroyed SafeSocket_" << std::endl;
}
};
typedef std::shared_ptr<SafeSocket_> SafeSocket;
To create/accept a new socket I use the following horrible code. What's worse even is that I need to use ClientSocket->Socket
all over the place.
SafeSocket ClientSocket = SafeSocket(new SafeSocket_(accept(ListenSocket, NULL, NULL)));
There must be a better way of handling this besides using a nice wrapper library.
Note: I'm aware there are nice wrapper libraries likes asio from boost, but I'm just messing around to get my head around some of the C++ basics.