93 lines
2.6 KiB
C++
93 lines
2.6 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;
|
|
}
|
|
|
|
/// @brief Close down the listener
|
|
SocketServer::~SocketServer()
|
|
{
|
|
close();
|
|
}
|
|
|
|
/// @brief returns true if we have a valid socket connection otherwise false
|
|
/// @return
|
|
bool SocketServer::isOkay(void)
|
|
{
|
|
return mIsOkay;
|
|
}
|
|
|
|
/// @brief This is the listener. It will wait for incoming connections.
|
|
/// When an incoming connection is received it will create a SocketConnectionReceiver object and call it's threadFunction to handle further interactions
|
|
/// such as transmitting a file.
|
|
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));
|
|
}
|
|
}
|
|
|
|
/// @brief Shut down the listener socket
|
|
/// @param
|
|
void SocketServer::close(void)
|
|
{
|
|
if(-1!=mSocketFileDescriptor)
|
|
{
|
|
::close(mSocketFileDescriptor);
|
|
mSocketFileDescriptor=-1;
|
|
}
|
|
}
|