gpt4 book ai didi

c++ - TCP 套接字(客户端-服务器)recv() 返回 -1 值

转载 作者:行者123 更新时间:2023-11-30 18:27:09 32 4
gpt4 key购买 nike

请指导我为什么阻塞函数recv()不等待来自客户端的消息。相反,它返回值-1。请指导我如何解决这个问题。

服务器代码(部分):

    (call to getaddrinfo) // struct addrinfo hints, *res

int sfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol);
if(sfd == -1)
{
printf("Socket creation failed .....");
exit(-3);
}
fcntl(sfd, F_SETFL, ~O_NONBLOCK);

if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
{
herror("setsockopt(SO_REUSEADDR) failed");
}

bind(sfd,res->ai_addr, res->ai_addrlen);
if(listen(sfd, BACKLOG)!=0)
{
printf("Listen Error");
exit(-4);
}
printf("\n\nListening on port: %s\n\n", argv[1]);
struct sockaddr_storage clientAddr;
socklen_t addrSize = sizeof(clientAddr);
int connFD = accept(sfd,(struct sockaddr*)&clientAddr, &addrSize); // connection successful
char buffer[10] = "Hello!";
write(connFD, buffer, sizeof(buffer)); // message sent to client
buffer[0] = '\0';
int bytesReceived;
if((bytesReceived = recv(sfd, buffer, sizeof(buffer), 0)) == -1) // Problem starts here
{
fprintf(stderr,"Could not retrieve message from client.");
exit(-5);
}


最佳答案

问题是你在错误的套接字(sfd)上调用recv,应该是(connFD)

修复:

if((bytesReceived = recv(connFD, buffer, sizeof(buffer), 0)) == -1)

关于c++ - TCP 套接字(客户端-服务器)recv() 返回 -1 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58893934/

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