tags:

views:

151

answers:

3

Hello All,

I have implemented the client server using socket programming in C on Unix OS. I have used the non blocking socket at client end. I want to implement the two way communication. But its working only with one way i.e. Client can read and write the data on server, but server can not read or write data on client.

Client

nread = recv(sock, ptr, nleft, MSG_DONTWAIT))
send(sock, ptr, nleft, 0))

Server

recv(sock, ptr, nleft, MSG_DONTWAIT))
SockWrite(sock, Message, dataLength)

Server is always facing problem in reading. Can any one explain me why and how to get rid of this?

+1  A: 

Await for socket ready for reading or writing using select() call.

elder_george
A: 

What is the return code to recv? Have you set the recv socket to non-blocking? In that case you are probably seeing EAGAIN, and you need to select() etc, or go back to blocking. I would not recommend ever ignoring return values to system calls.

swt
A: 

code samples

static void SetNonBlock(const int nSock, bool bNonBlock)
{
    int nFlags = fcntl(nSock, F_GETFL, 0);
    if (bNonBlock) {
     nFlags |= O_NONBLOCK;
    } else {
     nFlags &= ~O_NONBLOCK;
    }

    fcntl(nSock, F_SETFL, nFlags);
}

     ...
     SetNonBlock(sock, true);
     ...
    int code = recv(sock, buf, len_expected, 0);
    if(code > 0) {
            here got all or partial data
    } else if(code < 0) {
     if((errno != EAGAIN) && (errno != EINPROGRESS) ) {
                         here handle errors
     }
              otherwise may try again    
    } else if(0 == code) {
     FIN received, close the socket
    }
EffoStaff Effo