Aleksander Fimreite
Aleksander Fimreite

Reputation: 1449

SDL_Net Socket error on creation

I'm trying to create a socket for my SDL server. Problem is that I get an access violation crash because my socket called server is unable to open itself properly.

My class:

#pragma once
#include <SDL_net.h>
#include <thread>
#include <vector>
#include <string>
#include <iostream>
using namespace std;



const Uint16 SERVER_PORT = 1234;
const int TICKS_PER_SECOND = 1000;
const int REQUIRED_PLAYERS = 1;



class ServerTCP {
private:
    //Thread data
    thread *threadListen;
    bool threadExit;

    //Server data
    IPaddress serverIP;
    TCPsocket server;
    vector <string> feedback;

    //Client data
    vector <TCPsocket> clients;
    vector <string> events;

    static void threadLoop(ServerTCP *self);

public:
    ServerTCP();
    ~ServerTCP();
};

Source:

#include "ServerTCP.h"



ServerTCP::ServerTCP() {
    printf("Starting server...\n");
    if (SDLNet_ResolveHost(&serverIP, NULL, SERVER_PORT) == -1) {
        printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    }
    server = SDLNet_TCP_Open(&serverIP);
    if (!server) {
        printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
    }
    threadExit = false;
    threadListen = new thread(&ServerTCP::threadLoop, this);
}

ServerTCP::~ServerTCP() {
    printf("Shutting down server...\n");
    threadExit = true;
    threadListen->join();
    for (int i = 0; i < clients.size(); i++) {
        string warning = "Server has shut down, you was disconnected!\n";
        SDLNet_TCP_Send(clients[i], warning.c_str(), warning.size());
        SDLNet_TCP_Close(clients[i]);
    }
    SDLNet_TCP_Close(server);
}

void ServerTCP::threadLoop(ServerTCP *self) {
    printf("Waiting for players...\n");
    TCPsocket newClient;

    //Run thread until orderered to stop
    while (!self->threadExit) {

        //Look for new clients
        newClient = SDLNet_TCP_Accept(self->server);

        if (newClient) {
            self->clients.push_back(newClient);
            string warning = "You have connected to the server!\n";
            SDLNet_TCP_Send(newClient, warning.c_str(), warning.size());
            printf("Player %i has connected!\n", self->clients.size());
        }

        if (self->clients.size() >= REQUIRED_PLAYERS) {
            for (int i = 0; i < REQUIRED_PLAYERS; i++) {
                string warning = "You found an opponent!\n";
                SDLNet_TCP_Send(self->clients[i], warning.c_str(), warning.size());
                SDLNet_TCP_Close(self->clients[i]);
            }
        }
    }
}

Output:

Starting server...
SDLNet_TCP_Open: Couldn't create socket

Upvotes: 1

Views: 764

Answers (1)

Aleksander Fimreite
Aleksander Fimreite

Reputation: 1449

Never mind, I forgot I had the SDLNet_Init function in my sub class i removed in the server file.

Upvotes: 1

Related Questions