我正在尝试使用 C++/QtTcpSocket 为个人项目(多人国际象棋游戏)实现身份验证系统。
我的朋友建议了一种验证用户的方法,但我想问是否有更简单或更好的方法。来自 Python 背景,主要从事这个项目是为了加深对 C++ 的理解。
我将发布我朋友建议的方法,并寻求更好的解决方案。
他以一种伪代码方式构建它。服务器主要是构建的,我现在希望实现身份验证
*干杯
void process_packet(PACKET *pkt)
{
    switch(pkt->PacketID)
    {
        case 0: // let's say packet id 0 is the logon packet; packet contents are username and password
        {
            //let's say packet size is 101 bytes; packet id was already received, so get the other 100 bytes
            unsigned char BUFFER[101] = {0}; // i always add an extra byte to the end of the buffer to allow for off-by-one errors ^_^
            int result = recv_packet(pkt->cSocket, 100, BUFFER);
            if(result <= 0)
                return; // connection error; no packet data was received
            unsigned char *UserName = BUFFER+0; //+0 is not neccessary, but the username starts at the beginning. just getting the point across.
            unsigned char *PassWord = BUFFER+50;
            //side note: if we did "unsigned long *blah = BUFFER+4" or something, we would have to make sure the byte order is right. network byte order is BIG ENDIAN
            //  WINDOWS byte order is LITTLE ENDIAN
            result = QueryDatabase("SELECT username, password FROM chess_players WHERE username = '%s'", FILTER_INVALID_CHARS(UserName));
            // check result
            unsigned char ServerResponse[2] = {0};
            if(result['password'] == PassWord)
            {
                ServerResponse[0] = 1; // packet id will be 1. the next byte can be 1 or 0 to indicate logon success or failure.
                ServerResponse[1] = true; // so packet 0x0101 mean logon success, packet 0x0100 means logon failure
                send_packet(pkt->cSocket, ServerResponse, 2);
            } else {
                ServerResponse[0] = 1;
                ServerResponse[1] = false;
                send_packet(pkt->cSocket, ServerResponse, 2);
            }
        }
        break;
        default:
        {
            // received an unknown packet id; send a packet to the client that indicates an error_status_t
            unsigned char *ServerResponse[2] = {0};
            ServerResponse[0] = 2; // packet id 2 means server error
            ServerResponse[1] = 0; // error code 0 means 'unknown packet id'
            send_packet(pkt_cSocket, ServerResponse, 2);
        }
        break;
    }
    delete pkt; // must delete pkt, was created with 'new' in get_client_packets()
}