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

TCP sockets (client-server) recv() returning -1 value

本文关键字:recv 返回 服务器 套接字 客户端 TCP      更新时间:2023-10-16

请告诉我为什么阻止函数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("nnListening on port: %snn", 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] = '';
int bytesReceived;
if((bytesReceived = recv(sfd, buffer, sizeof(buffer), 0)) == -1)  // Problem starts here
{
fprintf(stderr,"Could not retrieve message from client.");
exit(-5);
}

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

修复:

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