Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // C++ headers
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <list>
- #include <chrono>
- // SDL headers
- #include <SDL2/SDL.h>
- #include <SDL2/SDL_net.h>
- using namespace std;
- volatile bool listenForClientConnections = true;
- void initSDL();
- TCPsocket createServerSocket();
- void listenForClients(TCPsocket socket)
- {
- static const char *LOGIN_SUCCESS_MSG = "LoggedIn";
- cout << "Listening for clients...\n";
- char clientName[32];
- while (listenForClientConnections)
- {
- this_thread::sleep_for(chrono::milliseconds(500));
- TCPsocket client = SDLNet_TCP_Accept(socket);
- if (client == nullptr)
- continue;
- cout << "A client has connected!" << endl;
- }
- }
- int main()
- {
- initSDL();
- TCPsocket serverSocket = createServerSocket();
- std::thread listenForClientsThread(listenForClients, serverSocket);
- getchar();
- listenForClientConnections = false;
- listenForClientsThread.join();
- SDLNet_TCP_Close(serverSocket);
- }
- void initSDL()
- {
- // initialize SDL
- if( SDL_Init(SDL_INIT_EVERYTHING) != 0 )
- {
- cout << SDL_GetError() << "\n";
- exit(-1);
- }
- atexit(SDL_Quit);
- // initialize SDLNet
- if( SDLNet_Init() != 0 )
- {
- cout << SDLNet_GetError() << "\n";
- exit(-1);
- }
- atexit(SDL_Quit);
- }
- TCPsocket createServerSocket()
- {
- IPaddress ip;
- ip.host = INADDR_ANY;
- ip.port = 12000;
- TCPsocket serverSocket = SDLNet_TCP_Open(&ip);
- if (serverSocket == nullptr)
- {
- cout << "Failed to create server socket: " << SDLNet_GetError() << endl;
- exit(-1);
- }
- return serverSocket;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement