86 lines
2.2 KiB
C++
86 lines
2.2 KiB
C++
#include <sstp/socketserver.hpp>
|
|
#include <sstp/socketconnectionreceiver.hpp>
|
|
|
|
/// @brief This will construct the socket listener. You must then call listen() to listen for connections
|
|
/// @param port
|
|
SocketServer::SocketServer(int port)
|
|
: mListenPort(port), mIsOkay(false), mSocketFileDescriptor(-1)
|
|
{
|
|
std::cout << "SocketServer()" << std::endl;
|
|
int opt=-1;
|
|
int result;
|
|
|
|
// create socket file descriptor
|
|
mSocketFileDescriptor = ::socket(AF_INET,SOCK_STREAM,0);
|
|
if(0==mSocketFileDescriptor)return;
|
|
|
|
// attach socket to port
|
|
result = ::setsockopt(mSocketFileDescriptor, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
|
|
if(result)
|
|
{
|
|
close();
|
|
return;
|
|
}
|
|
|
|
// bind socket to network address and port
|
|
mInternalSocketAddress.sin_family = AF_INET;
|
|
mInternalSocketAddress.sin_addr.s_addr=INADDR_ANY;
|
|
|
|
|
|
mInternalSocketAddress.sin_port = htons(mListenPort);
|
|
result = ::bind(mSocketFileDescriptor,(struct sockaddr*)&mInternalSocketAddress,sizeof(mInternalSocketAddress));
|
|
if(result)
|
|
{
|
|
close();
|
|
return;
|
|
}
|
|
mIsOkay=true;
|
|
}
|
|
|
|
SocketServer::~SocketServer()
|
|
{
|
|
std::cout << "~SocketServer()" << std::endl;
|
|
close();
|
|
}
|
|
|
|
bool SocketServer::isOkay(void)
|
|
{
|
|
return mIsOkay;
|
|
}
|
|
|
|
void SocketServer::listen(void)
|
|
{
|
|
while(isOkay())
|
|
{
|
|
std::cout << "Listening on port " << mListenPort << std::endl;
|
|
int result = ::listen(mSocketFileDescriptor, MAX_CONNECTIONS);
|
|
if(result)
|
|
{
|
|
std::cout << "Error listening on port " << mListenPort << std::endl;
|
|
close();
|
|
return;
|
|
}
|
|
struct sockaddr_in internalSocketAddress;
|
|
socklen_t addressLength = sizeof(internalSocketAddress);
|
|
|
|
int socket = ::accept(mSocketFileDescriptor, (struct sockaddr*)&internalSocketAddress, &addressLength);
|
|
if(result)
|
|
{
|
|
std::cout << "Error accepting connection " << mListenPort << std::endl;
|
|
close();
|
|
return;
|
|
}
|
|
SocketConnectionReceiver socketConnectionReceiver(socket, internalSocketAddress);
|
|
mExecutionThreads.push_back(std::thread(&SocketConnectionReceiver::threadFunction, &socketConnectionReceiver, 0));
|
|
}
|
|
}
|
|
|
|
void SocketServer::close(void)
|
|
{
|
|
if(-1!=mSocketFileDescriptor)
|
|
{
|
|
::close(mSocketFileDescriptor);
|
|
mSocketFileDescriptor=-1;
|
|
}
|
|
}
|