创建SDL_Net套接字时出错

SDL_Net Socket error on creation

本文关键字:出错 套接字 Net SDL 创建      更新时间:2023-10-16

我正在尝试为我的SDL服务器创建一个套接字。问题是,我得到一个访问冲突崩溃,因为我的套接字称为server无法正常打开自己。

我的类:

#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();
};
源:

#include "ServerTCP.h"

ServerTCP::ServerTCP() {
    printf("Starting server...n");
    if (SDLNet_ResolveHost(&serverIP, NULL, SERVER_PORT) == -1) {
        printf("SDLNet_ResolveHost: %sn", SDLNet_GetError());
    }
    server = SDLNet_TCP_Open(&serverIP);
    if (!server) {
        printf("SDLNet_TCP_Open: %sn", 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]);
            }
        }
    }
}
输出:

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

没关系,我忘了我在服务器文件中删除了子类中的SDLNet_Init函数