我有一个服务器,每 5 秒向客户端发送一次数据。我希望客户端在 read() 上阻塞,直到服务器发送一些数据然后打印它。我知道默认情况下 read () 是阻塞的。我的问题是我的客户没有阻塞 read()。这很奇怪,这似乎不是一个正常问题。
我的代码在无限循环中打印“Nothing came back”。我在一台linux机器上,用c编程。我的代码片段如下。请指教。
while(1)
{
n = read(sockfd, recvline, MAXLINE);
if ( n > 0)
{
recvline[n] = 0;
if (fputs(recvline, stdout) == EOF)
printf("fputs error");
}
else if(n == 0)
printf("Nothing came back");
else if (n < 0)
printf("read error");
}
return;
最佳答案
可能有几个原因,在不同的地方可能有几个异常(exception):
检查您创建的套接字:
sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd==-1) { perror("Create socket"); }
您和在使用之前显式启用阻塞模式:
// Set the socket I/O mode: In this case FIONBIO // enables or disables the blocking mode for the // socket based on the numerical value of iMode. // If iMode = 0, blocking is enabled; // If iMode != 0, non-blocking mode is enabled. ioctl(sockfd, FIONBIO, &iMode);
或者您可以使用
setsockopt
如下:struct timeval t; t.tv_sec = 0; tv_usec = 0; setsockopt( sockfd, // Socket descriptor SOL_SOCKET, // To manipulate options at the sockets API level SO_RCVTIMEO,// Specify the receiving or sending timeouts const void *(&t), // option values sizeof(t) );
检查读取函数调用(错误原因)
n = read(sockfd, recvline, MAXLINE); if(n < 0){ perror("Read Error:"); }
同时检查服务器代码!:
May your server send some blank(non-printable, null, enter) charter(s). And your are unaware of this. Bug you server code too.
Or your server terminated before your client can read.
还有一个有趣的事情,试着理解一下:
When you call N
write()
at server its not necessary there should be Nread()
call at other side.
关于c - read() 在套接字编程中不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773509/