TCP套接字(客户端-服务器)recv()返回-1值
TCP sockets (client-server) recv() returning -1 value
请告诉我为什么阻止函数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)
相关文章:
- 在 Linux 中关闭 UDP 套接字后,recv 不会返回
- 为什么套接字中的 recv() 函数不返回任何内容?
- 设置SO_RCVTIMEO时,为什么recv返回-1并且errno=EINTR
- TCP套接字(客户端-服务器)recv()返回-1值
- 为什么 sys 套接字 recv 函数不填充数据但返回字节长度?
- C++ 即使数据可用,Windows recv() 也不会返回
- Linux 套接字 recv 返回 -1,errno 110 连接超时
- TCP 服务器/客户端:客户端 recv() 返回空白缓冲区
- 如果send()返回x字节,则recv()在一个呼叫中获取相同数量的字节
- c++winsock-recv()返回不正确且奇怪的缓冲区
- Winsock recv() 返回不正确的数据
- 找到0x0000字节后的recv返回
- C++ WinSock Recv 在接收 0 数据时终止线程而不是返回错误代码
- 带有 MSG_PEEK 的 C 'recv'不返回 -1
- Recv 未返回足够的字节(二进制 http 响应)
- 带有 MSG_PEEK 的 recv() 显示完整消息,但正常返回'would block'
- 为什么 select() 返回 1 而 recv() 返回 0
- setsockopt() 在设置大套接字 recv 缓冲区时不返回错误
- TCP Recv使用select()返回1字节读取
- Unix套接字在C++中编程,recv返回0,但仍在接收数据,但有时接收的数据比发送的多