Q-bertsuit
Q-bertsuit

Reputation: 3437

Non-blocking socket receive

I have a simple server program that looks like the code below:

// create, bind, listen accept etc..

while(1)
{
    UpdateData();
    int ret = send(sock, data, dataLength , 0);

    // Check if client sent "Abort" and if so, break.
}

Is it possible to check if any data has arrived from the client without blocking, so that the server can continuously dump data to the client?

Upvotes: 0

Views: 1353

Answers (2)

Stargateur
Stargateur

Reputation: 26765

Yes of course, there are a lot of solutions, AFAIK:

Not all available for all OS.

Upvotes: 3

If your gonna define a non-blocking socket, you should add SOCK_NONBLOCK value in socket-type parameter when open a socket. for example this statement open a RAW socket in which can read and write TCP packets in non-blocking mode :

recv_socket = socket(AF_INET, SOCK_RAW | SOCK_NONBLOCK
                         , IPPROTO_TCP);

Then you can call read function as bellow :

typedef struct
{
    struct iphdr ip;
    struct tcphdr tcp;
    char datagram[DATAGRAM_SIZE];
} TCP_PACKET;

int ret_read = 0;
TCP_PACKET recv_packet;

ret_read = read(recv_socket, reinterpret_cast<void*>(&received_packet)
, sizeof(received_packet));

if(ret_read >= 0)
{
    // read occured in success
}

Notice : never use of const-size in read :

ret_read = read(recv_socket, reinterpret_cast<void*>(&received_packet)
, 65536);    // makes segmentation fault

it makes segmentation fault while reading packets. just use of sizeof.

Upvotes: 1

Related Questions