⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.cpp

📁 wyd server 753 development with c++ and codeblocks
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/* by My Destiny Team */

#include "server.h"
#include "packets.h"
// Informacoes do servidorcServer Server;// Lista dos nomes dos personagens basesconst char *nameBase[MAX_CHARBASE] = {    "character/transknight.txt",    "character/foema.txt",    "character/beastmaster.txt",    "character/hunter.txt"};
cServer::cServer() : cSocket()
{
    currUser = 0;    accListSize = 0;    srvIndex = INVALID_SERVERINDEX;    memset(accList, 0, sizeof(accList));    memset(charBase, 0, sizeof(charBase));    memset(language, 0, sizeof(language));
}

cServer::~cServer()
{    u32 x;    sAccountList **acc = &accList[0][0];    // Deleta todos os clients conectados    for(x = 0; x < accListSize; acc++)        if(*acc != NULL)            x++, delete *acc, *acc = NULL;    // Deleta os ponteiros das strings    for(x = 0; x < MAX_LANGUAGE; x++)        if(language[x] != NULL)            delete language[x];
}

// Inicia o servidor
bool cServer::Init()
{
    if(/* init server */
        !cServer::ReadConfig()      ||
        !cSocket::ReadConfig()      ||        !ReadServerList()           ||        !ReadAdminList()            ||
        !StartServer()
      )
    { /* falha ao iniciar o serv */
        return false;
    }    for(u32 x = 0; x < MAX_CHARBASE; ++x)        ReadCharacter(nameBase[x], &charBase[x]);
    Log(NORMAL, GetMessage(INITSERVER), GetServerIP(), GetServerPort());
    return true;
}
// Le o arquivo de configuracao do servidor//// Retorna false se ocorreu um erro// Retorna true se leu com sucessobool cServer::ReadConfig(){    const char *def = "server.ini";    FILE *fp = fopen(def, "r");    if(fp == NULL)    { /* not found */        Log(WARN, GetMessage(ERRORLOADED), def);        return false;    }    while(fgets(buf, sizeof(buf), fp))    {        if(buf[0] == '#' || buf[1] == '#' || buf[0] == '\n')            continue;        if(sscanf(buf, "%s = %s", cmd, val) != 2)            continue;        if(strcmp(cmd, "ServerIndex") == 0)            srvIndex = atoi(val);    }    fclose(fp);    Log(NORMAL, GetMessage(LOADEDFILE), def);    return true;}// Le a lista dos servidores que podem se conectar//// Retorna false se ocorreu um erro na leitura// Retorna true se o arquivo foi lido com sucessobool cServer::ReadServerList(){    const char *def = "../serverlist.txt";    FILE *fp = fopen(def, "r");    if(fp == NULL)    { /* not found */        Log(WARN, GetMessage(ERRORLOADED), def);        return false;    }    memset(srvList, 0, sizeof(srvList));    u32 sIndex = 0, pIndex = 0;    while(fgets(buf, sizeof(buf), fp))    {        if(buf[0] == '#' || buf[0] == '\n')            continue;        sscanf(buf, "%d\t%d\t%s", &sIndex, &pIndex, cmd);        if(sIndex == srvIndex && pIndex < 10)            strcpy(srvList[pIndex], cmd);    }    fclose(fp);    Log(NORMAL, GetMessage(LOADEDFILE), def);    return true;}// Le a lista dos admins que podem se conectar//// Retorna false se ocorreu um erro na leitura// Retorna true se o arquivo foi lido com sucessobool cServer::ReadAdminList(){    const char *def = "../adminlist.txt";    FILE *fp = fopen(def, "r");    if(fp == NULL)    { /* not found */        Log(WARN, GetMessage(ERRORLOADED), def);        return false;    }    memset(adminList, 0, sizeof(adminList));    u32 Index = 0;    while(fgets(buf, sizeof(buf), fp))    {        if(buf[0] == '#' || buf[1] == '#' || buf[0] == '\n')            continue;        if(sscanf(buf, "%d\t%s", &Index, cmd) == 2)            if(Index < 10)                strcpy(adminList[Index], cmd);    }    fclose(fp);    Log(NORMAL, GetMessage(LOADEDFILE), def);    return true;}// Le o arquivo de idiomas//// Retorna false se ocorreu um erro// Retorna true se leu com sucessobool cServer::ReadLanguage(){    FILE *fp = fopen("language.txt", "r");    if(fp == NULL)    { /* not found */        wxMessageBox("language.txt not found.",            "Error: fopen", wxOK | wxICON_ERROR);        return false;    }    u32 index = 0;    char buflang[96];    while(fgets(buf, sizeof(buf), fp))    {        if(buf[0] == '#' || buf[0] == '\n')            continue;        if(sscanf(buf, "%03d\t\"%095[^\"]", &index, buflang) != 2)            continue;        if(index < MAX_LANGUAGE)        { /* index valido */            int len = strlen(buflang);            char *str = new char[len + 1];            strcpy(str, buflang);            language[index] = str;        }    }    fclose(fp);    return true;}// Abre o arquivo da conta ou do personagem//// Retorna NULL se nao foi possivel abrir o arquivo// Retorna o ponteiro do arquivo se abriu com sucessoFILE* cServer::OpenFile(char *name, const char *s, u32 x){    return fopen(GetFileDir(name, x), s);}// Retorna o diretorio completo da conta/personagemconst char* cServer::GetFileDir(char *name, u32 x){    static char dir[32];    for(u32 y = 0; y < strlen(name); y++)        if(!isalnum(name[y]))            name[y] = 'x';    if(isalpha(name[0]))    { // Primeiro caracter é uma letra        sprintf(dir, "./%s/%c/%s", x == ACCOUNT ?            "account" : "character", toupper(name[0]), name);    }    else    { // Primeiro caracter é um numero        sprintf(dir, "./%s/etc/%s", x == ACCOUNT ?            "account" : "character", name);    }    return dir;}// Adiciona um novo client na lista de conectadosvoid cServer::AddAccount(sAccountList *_acc){    sAccountList **acc = &accList[0][0];    for(u32 y = 0; y < 10; y++)    { // Loop dos servidores        for(u32 x = 0; x < FD_SETSIZE; acc++, x++)        { // Verifica se este id esta vazio            if(*acc == NULL)            { // Adiciona o ponteiro na lista                *acc = _acc;                // Aumenta o numero de clients conectados                accListSize++;                return ;            }        }    }    // Lista esta cheia    Log(WARN, "cServer::AddAccount failed.");}// Verifica se o client esta na listasAccountList* cServer::ContainsAccount(const char *name){    sAccountList **acc = &accList[0][0];    for(u32 x = 0; x < accListSize; acc++)    { // Verifica se existe um client neste id        if(*acc != NULL)        { // Verifica o nome de usuario do client            if(strcmp((*acc)->name, name) == 0)                return *acc;            x++;        }    }    // Nenhum client foi encontrado    return NULL;}// Procura e deleta o client da listavoid cServer::DeleteAccount(u16 gsindex, s16 clientid){    sAccountList **acc = &accList[0][0];    for(u32 x = 0; x < accListSize; acc++)    { // Verifica se existe um client neste id        if(*acc != NULL)        { // Verifica se é o client que tem que deletar            if((*acc)->gsIndex == gsindex && clientid == -1 ? true : (*acc)->clientID == clientid)            { // Deleta o ponteiro e zera ele                delete *acc, *acc = NULL;                // Diminui o numero de clients conectados                accListSize--;                return ;            }            x++;        }    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -