gpt4 book ai didi

c++ - 在 Qt 服务器上验证用户

转载 作者:太空狗 更新时间:2023-10-29 23:07:19 25 4
gpt4 key购买 nike

我正在尝试使用 C++/QtTcpSocket 为个人项目(多人国际象棋游戏)实现身份验证系统。

我的 friend 提出了一种验证用户的方法,但我想问问是否有更简单或更好的方法。来自 Python 背景,主要从事此项目以加深对 C++ 的理解。

我会把我 friend 建议的方法发上来,寻求更好的解决方案。

他以一种伪代码的方式构建了它。服务器基本搭建完成,现在希望实现Authentication

*干杯

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()
}

最佳答案

这看起来很 C 风格,不像 Qt 做事的方式。您的问题没有通用的答案,但我的建议如下:

newConnection() QTcpServer 的信号.您的处理程序必须调用 nextPendingConnection()让下一个客户在队列中等待。您要做的第一件事可能是您的用户身份验证。一旦通过身份验证,您就可以将 QTcpSocket 保留在您的事件连接列表中。

看看例如财富客户端/服务器示例如何实际写入/读取数据包。您可能还想查看流运算符 <<序列化你的对象。与您发布的低级方法相比,这更容易且更不容易出错。此外,QDataStream 将自动处理主机和网络字节顺序。

关于c++ - 在 Qt 服务器上验证用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13199267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com