You can either:
Set the socket into non-blocking mode, with ioctl() and the F_NBIO flag, in which case read() will return -1 with errno set to EWOULDBLOCK/EAGAIN if there is no data, or, more probably
Set a read timeout, with setsockopt() and the SO_RCVTIMEO option.
NB your current code is flawed in that it doesn't handle end of stream (read() returns zero) at all, and in that treats all read() errors alike. They aren't. Some, such as ECONNRESET, are fatal to the connection and should cause its closure.