多个客户端未连接且无法同时通信

时间:2014-07-04 11:06:49

标签: c sockets socketserver

以下是我为多个客户编写的服务器代码。但如果我想将它与第二个客户端连接,我无法同时连接它。首先,我需要关闭第一个客户端,然后只有我可以连接并与第二个客户端通信。我认为在使用pthread_join时遇到了一些问题。不确定究竟是什么问题。我想让服务器同时为多个客户端工作。

#include<stdio.h>
#include<string.h>    //strlen
#include<stdlib.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write
#include<pthread.h> //for thread


 #define MAX_CLIENTS 5


//the thread function
void *new_connection_handler(void *);

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c , *new_sock;
    struct sockaddr_in server , client;


    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }


    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );
    bzero (&server.sin_zero, 8);



    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }


    //Listen
    listen(socket_desc , MAX_CLIENTS);



    //Accept and incoming connection
    printf("Waiting for incoming connections\n");




    c = sizeof(struct sockaddr_in);
    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        printf("Connection accepted");



        pthread_t thread_id;
        new_sock = malloc(1);
        *new_sock = client_sock;



        if( pthread_create( &thread_id , NULL ,  new_connection_handler , (void*) new_sock) < 0)
        {
            perror("could not create thread");
            return 1;
        }



     printf("Handler assigned\n");
    }


    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }

    return 0;
}


void *new_connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];



    //Send some messages to the client
    message = "This is connection handler\n";
    write(sock , message , strlen(message));


    message = "Type something \n";
    write(sock , message , strlen(message));


    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , strlen(client_message));
    }



    if(read_size == 0)
    {
        printf("Client disconnected\n");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    //Free the socket pointer
    free(socket_desc);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

无需加入所有主题。分离的线程适用于此任务。

我假设你真的在pthread_join循环中调用while (accept(..)),否则你的描述没有多大意义。如果是这种情况,只需将其替换为pthread_detach

如果要在退出之前等待所有线程终止,请使用pthreads条件变量来计算活动线程。在你的情况下,主程序永远不会退出,所以你可以简单地忽略这个问题。