C, socket programming: Connecting multiple clients to server using select()

后端 未结 5 1941
有刺的猬
有刺的猬 2021-02-02 00:23

I\'m trying to make a server that can be connected to by multiple clients. Here\'s my code so far:

Client:

int main(int argc, char **argv) {

  struct so         


        
相关标签:
5条回答
  • 2021-02-02 01:01

    1) It is a good practice to use PF_INET(protocol family) rather than
    AF_INET(address family) during the Socket creation .

    2) within the while(1) loop
    each time it is advisable to make your readfds empty by using FD_ZERO(&readfds). in the recv() call you should use i rather than clientsocks[i] you have to check return value of recv is negative(which indicating error in reading) if that is the case you do not have to print the message. during printing the message make sure the stdout/server is ready for writing anything to it which you can do it by using writefds (3rd argument of select).

    0 讨论(0)
  • 2021-02-02 01:02

    You need to check for limit <= 0 in your read loop, before you call read.

    0 讨论(0)
  • 2021-02-02 01:02

    In the while loop for the server, change the code to do recv(i) instead of recv(clientsocks[i]). I have implemented this code and it works with this change.

    0 讨论(0)
  • 2021-02-02 01:05

    Two issues in your code:

    • You should do recv(i, ...) instead of recv(clientsock[i], ...)

    • After that you do not check if recv() failed, and therefore printf() prints out the uninitialised buffer message, hence the garbage in the output

    0 讨论(0)
  • 2021-02-02 01:13

    I replaced the else with the below and it works

     } else {
    /*                  int messageLength = 5;
                        char message[messageLength+1];
                        int in, index = 0, limit = messageLength+1;
    
                        memset ( &message[index] , 0, sizeof ( message [index] ) );
    
                        while ((in = recv(i, &message[index], limit, 0)) > 0) {
                            index += in;
                            limit -= in;
                        }
    
                        printf("%d\n", index);
                        printf("%s\n", message);
    */
                        bzero(buf, sizeof(buf));
                        if ((rval = read(i, buf, 1024)) < 0)
                            perror("reading stream message");
                        else if (rval == 0)
                            printf("Ending connection\n");
                        else
                            printf("-->%s\n", buf);
    
                    }
    
    0 讨论(0)
提交回复
热议问题