tags:

views:

96

answers:

2

There is a simple Client-Server program.

  • The server is started $./server 5000
  • The client is also connected to server.. $./client 127.0.0.1 5000
  • The client enters a string
  • Client has the message "I got your message" displayed on his terminal & server displays the entered string by the client

The issue is that when I run client by doing $./client 127.0.0.1 5000. I get this in server side terminal.

Before Listen 
After Listen 
Before accept 
After accept 
Before read

Then only when I enter the message on client screen and then press enter. I get this displayed..

Here is the message: This is a message

Why is that the code goes into wait state before read() call.. Shouldnt it just read nothing and return 0..

I am wrong somewhere conceptually. Pls help me out..

Relevant code of Client:-

if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0) 
        error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    printf("%d\n",n);
    if (n < 0) 
        error("ERROR reading from socket");
    printf("%s\n",buffer);

Relevant Server code:-

if (bind(sockfd, (struct sockaddr *) &serv_addr,
                sizeof(serv_addr)) < 0) 
        error("ERROR on binding");
    printf("Before Listen ");
    listen(sockfd,5);
    printf("After Listen ");
    clilen = sizeof(cli_addr);
    printf("Before accept ");
    newsockfd = accept(sockfd, 
            (struct sockaddr *) &cli_addr, 
            &clilen);
    printf("After accept");
    if (newsockfd < 0) 
        error("ERROR on accept");
    bzero(buffer,256);
    printf("Before read");
    n = read(newsockfd,buffer,255);
    if (n < 0) error("ERROR reading from socket");
    printf("Here is the message: %s\n",buffer);
    n = write(newsockfd,"I got your message",18);
    if (n < 0) error("ERROR writing to socket");
+4  A: 

By default, sockets are created as blocking sockets and a read call will block (wait) until there's data to be read.

Matti Virkkunen
We typed nearly an identical answer :) +1
Tim Post
ohk. I didnt know this.. Thanx..
shadyabhi
A: 

You if you don't want read to block you must disable BLOCKING mode.

int flags;

flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);

Also note that read() and write() do not guarantee that they will return the amount you requested. That is why many people implement readall() or writeall() functions.

Eric des Courtis