简体   繁体   中英

Reading data from a socket in C

I'm using select to read data from the user and also check for incoming connections. This is my code,

 .....
    socket has been created and is listening


        while(1){
            printf("$ ");
            fflush(stdout);
            read_fds = master;

            if(select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1){
                perror(" Select failed: ");
                exit(-1);
            }
            for(int i=0; i <= fdmax; i++){

                if (FD_ISSET(i, &read_fds)) {

                    if(i == STDIN){//process user input

                        char usrInputStr[256];
                        if ((rbytes = read(STDIN, usrInputStr, 256)) < 0) {
                            perror("Read error: ");
                            exit(-1);
                        }

                        fgets(usrInputStr, sizeof(usrInputStr), stdin);


                        printf("%s\n",usrInputStr);

 }else if(i == sockServer){//also need to check that this is a server
                    //handle new connection
                    addrlen = sizeof(remoteaddr);
                    sockClient = accept(sockServer, (struct sockaddr*)&remoteaddr, &addrlen);
                    if(sockClient < 0){
                        perror("Accept failed: ");
                        exit(-1);
                    }
                    FD_SET(sockClient, &master);
                    if (sockClient > sockServer)
                    {
                        fdmax = sockClient;
                    }

                }

The code doesn't print the user input back on the I/O. Can't seem to understand what's going wrong.

Three obvious things jump out:

  1. if (sockClient > sockServer) should probably be if (sockClient > fdmax) .

  2. You read from stdin twice, one with read (which is good) and once with fgets (which is bad).

  3.   printf("%s\\n",usrInputStr); 

    The %s format specifier is for C-style strings, not arbitrary arrays of characters. You didn't do anything with rbytes , so how could it possibly know how many characters to print?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM