在我的 C 应用程序中,我通过以下方式等待套接字上的数据:
printf("Opening socket and wait for data.n");
while (i < 5)
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
bzero(buffer, 64);
n = read(connection_fd,buffer,64);
if (n < 0) printf("ERROR reading from socket");
printf("Here is the message of length %d bytes:nn", n);
for (int i = 0; i < n; i++)
{
printf("%02X", buffer[i]);
}
printf("nn");
break;
}
i++
}
这意味着我从套接字读取了 5 次数据,但是,从外观上看,我似乎打开了 5 个不同的连接,对吗?是否可以只打开连接一次,使其保持活动状态,然后检查此连接上是否有任何可用数据?
谢谢,帕特里克!
你的代码需要一些重组,你应该只接受每个新连接一次:
while (1) {
connection_fd = accept(socket_fd, ...);
/* check for errors */
if (connection_fd < 0) {
/* handle error */
}
/* note this could block, if you don't want
that use non-blocking I/O and select */
while ((n=read(connection_fd, buf, ...)) > 0) {
/* do some work */
}
/* close fd */
close(fd);
}
当然。为此,您可能希望将参数交换到两个while()
循环:
while ((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
while (i < 5)
{
...
是的。卸下while (i<5)
位。read
后,如果需要,您可以读取更多数据。
很简单。将调用 accept 函数的语句移到循环之外,然后使用相同的套接字描述符调用 read。
if (n < 0) printf("ERROR reading from socket");
为什么要继续?要么break;
循环,要么continue;
新连接。