0

I am trying to use the poll function to make a client accept the input from the server and print it out, or accept the input from the keyboard and send it to the server. The output has the file descriptor of the socket that carries the info from the server, but I do not know what file descriptor I should give it to the input of the pollfd struct(the part that accepts the input from the keyboard). Right now i gave the same file descriptor to both of them. here is my code for the client:

void error(const char *msg)
{
    perror(msg);
    exit(0);
}


void chat( int sockfd)
{

    struct pollfd thing[2];

    thing[0].fd = sockfd;
    thing[0].events = POLLRDNORM | POLLERR;
    thing[0].revents = 0;
    thing[1].fd = sockfd;
    thing[1].events = POLLERR | POLLWRNORM;
    thing[1].revents = 0;
    char buffer[256];
    int n;

    while(strcmp(buffer, "quit")!=0)
    {
       int r = poll(thing, 2, 1000);
       if(r<0)
       {
         perror("poll");
         sleep(1);}

        bzero(buffer, 256);
        if(thing[0].revents & POLLRDNORM)
        {
           n = read(sockfd,buffer,255);
           if (n < 0)
              error("ERROR reading from socket");
           printf("the message is : %s\n",buffer);
         }


        else if(thing[1].revents & POLLWRNORM)
        { bzero(buffer, 256);
          fgets(buffer,255,stdin);
          n = write(sockfd,buffer,strlen(buffer));
          if (n < 0)
             error("ERROR writing to socket");}
        else continue;
    }
}
SSC
  • 1,311
  • 5
  • 18
  • 29
  • Likely you should poll for POLLRDNORM on server socket FD and stdin FD (use fileno() for that, but for stdin == 1). Then when input arrives on one of the FDs you read it and then perform corresponding action (print received from the server or send input to the server) – user3159253 Dec 10 '14 at 05:52
  • Also if you'd wish to build up a completely non-blocking application, you should poll for POLLWRNORM on socket FD and write data in non-blocking mode. – user3159253 Dec 10 '14 at 05:55
  • See http://stackoverflow.com/questions/3153939/properly-writing-to-a-nonblocking-socket-in-c for examples of non-blocking socket writing – user3159253 Dec 10 '14 at 05:58

1 Answers1

0

I do not know what file descriptor I should give it to the input of the pollfd struct(the part that accepts the input from the keyboard).

If the keyboard is connected to stdin, you can use STDIN_FILENO from <unistd.h> as well as 0.

Armali
  • 18,255
  • 14
  • 57
  • 171