C++ 服务器正确回复

C++ Server reply properly

我想制作一个回复我的套接字的服务器。 我有这样的代码:

#define DEFAULT_BUFLEN 512

    /*...*/
int iResult;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;  

    /*...*/     

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (recvbuf == "hello"){
    iSendResult = send(ClientSocket, "Hi Client", sizeof("Hi Client"), 0);

}else {printf("[ERROR]Unexpected Socket.\n"); }

现在,它不起作用。我现在不知道为什么。我试着在网上搜索一些东西(结果很差)。 我怎样才能让它发挥作用?我愿意更改所有代码。

您不能将 C 风格的字符串与 == 进行比较。您正在将缓冲区的地址与静态字符串文字的地址进行比较,后者始终不相等。

您还需要处理这样一个事实,即每次从流套接字读取(假设这就是它)可能会提供比您预期更多或更少的数据。

更正确的比较可能是

if (iResult < 0) {
    // Some kind of read error, check errno for details
} else if (iResult == 0) {
    // Socket was closed
} else if (iResult < 5) {
    // Not enough input: read some more or give up
} else if (std::equal(recvbuf, recvbuf+5, "hello")) {
    // Expected input: there might be more data to process
} else {
    // Unexpected input
}