Skip to content

Instantly share code, notes, and snippets.

@TheOnlyArtz
Created May 16, 2020 08:59
Show Gist options
  • Save TheOnlyArtz/29c1ceb7fb769003cb5189f53abdd04d to your computer and use it in GitHub Desktop.
Save TheOnlyArtz/29c1ceb7fb769003cb5189f53abdd04d to your computer and use it in GitHub Desktop.
#include "LoginRequestHandler.h"
#include "Server.h"
/*
This is some boilerplate code to be honest
taken from: https://benshokati.blogspot.com/2012/06/how-to-create-client-server-network-for.html
*/
Server::Server()
{
/*Database stuff goes here*/
m_database = new SqliteDatabase();
m_database->initializeDatabase();
m_handlerFactory = new RequestHandlerFactory(m_database);
WSADATA wsaData;
ListenSocket = INVALID_SOCKET;
ClientSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error :%d", iResult);
exit(1);
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
printf("Getaddrinfo failed with error: %d", iResult);
WSACleanup();
exit(1);
}
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ld", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
exit(1);
}
u_long iMode = 1;
iResult = ioctlsocket(ListenSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR)
{
printf("ioctlsocket failed with error :%d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
exit(1);
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
exit(1);
}
// no longer need address information
freeaddrinfo(result);
// start listening for new clients attempting to connect
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
exit(1);
}
}
// accept new connections
bool Server::acceptNewClient(unsigned int& id)
{
// if client waiting, accept the connection and save the socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket != INVALID_SOCKET)
{
//disable nagle on the client's socket
char value = 1;
setsockopt(ClientSocket, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
LoginRequestHandler* newHandler = new LoginRequestHandler(m_handlerFactory);
// insert new client into session id table
m_clients.insert(std::pair<SOCKET, IRequestHandler*>(ClientSocket, newHandler));
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment