There is a thread likes this:
{
......
while (1)
{
recv(socket, buffer, sizeof(buffer), 0);
......
}
close(socket
Also, set your socket to be nonblocking:
int listen_sd = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (listen_sd < 0) {
perror("socket() failed");
}
int on = 1;
//set socket to be non-blocking
int rc = ioctl(listen_sd, FIONBIO,(char *)&on);
if (rc < 0) {
perror("ioctl() failed");
close(listen_sd);
}
Then, you can call recv() on the socket, and it won't block. If there's nothing to read then the ERRNO global variable is set to the constant EWOULDBLOCK
int rc = recv(listen_sd, buffer, sizeof(buffer), 0);
if (rc < 0) {
if (errno != EWOULDBLOCK) {
perror("recv() failed");
}
}