1

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?

Nifle
  • 11,745
  • 10
  • 75
  • 100
Sachin
  • 20,805
  • 32
  • 86
  • 99
  • 3
    Posting complete source code will increase your chances of receiving answers. – JesperE Oct 12 '09 at 11:13
  • 1
    Can you clarify - do you mean that the client can "recv data from the server" and "send data to the server"? If that is the case, then it seems like your server is able to both send/recv data from the client. – poundifdef Oct 12 '09 at 19:42
  • yes I want a two way communication berween client and server. – Sachin Oct 13 '09 at 05:26

3 Answers3

1

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

elder_george
  • 7,849
  • 24
  • 31
0

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.

0

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
    }
Test
  • 1,697
  • 1
  • 11
  • 10