【问题标题】:Simple Linux C/S socket with pthread带有 pthread 的简单 Linux C/S 套接字
【发布时间】:2012-02-16 03:49:38
【问题描述】:

所以我想在 linux 内核 2.6.x 下使用套接字将多个客户端连接到服务器。 当客户端连接时,服务器将向客户端发送欢迎消息,以显示在标准输出或任何内容上的方式。因此,当连接打开时,一个线程被分配给一个可能向客户端发送欢迎消息的函数非常客户端。当我使用另一个处理器来完成这项工作时,它很好。但是,当我切换到 pthread 方式时,客户端无法从服务器获取任何东西。此时,我检查了 netstat,连接仍然on.so 我的代码来了:

client.c

// to make long story short,
// i'll just omit most of declarations and stuff that is irrelavent to the problem
#define PORT 12345
#define IP_ADDR "127.0.0.1"
void *process_to_server(int socket);
int main(){
   // i'll skip building socket for your convinence
   process_to_server(socket_server);

}
void *process_to_server(int socket){
   ssize_t size=0;
   char buffer[1024];
   size=read(socket,buffer,1024);
   write(1,buffer,size+1);// output the welcome message to the client's standard output
}

服务器.c

#define PORT 12345
void *process_to_client(int socket);
int main(){
   // same spirit as above
   while(1){
     int addrlen=sizeof(struct sockaddr);
     socket_client = accept(socket_server,(struct sockaddr*)&client_addr,&addrlen);
     if(socket_client<0) continue;

     pthread_t pth;
     close(socket_server);
     pthread_create(&pth,NULL,(void*)&process_to_client,&socket_client);
     }
}

void *process_to_client(int socket){
    char buffer[1024];
    sprintf(buffer,"Hello There\n");
    write(socket,buffer,1024);
}

【问题讨论】:

  • 为什么是close(socket_server);

标签: c linux sockets


【解决方案1】:

您正在将&amp;socket_client 转移到工作线程,但使用线程函数参数就像是socket_client

你可以这样做:

int main() {
/*...*/
pthread_create(&pth,NULL,(void*)&process_to_client,(void*)socket_client);
/*...*/
}

void *process_to_client(void* pvsocket) {
int socket = (int) pvsocket;
/* same as before */
}

同时关闭侦听套接字将使接受的连接保持打开状态。您将能够继续与已连接的客户端通信,但不会接受进一步的传入连接。通信完成后工作线程应该关闭socket_client

【讨论】:

    【解决方案2】:

    你的线程函数的参数是一个指针,但是你直接把它当作一个整数来使用。像这样改变你的线程函数:

    void *process_to_client(void *socket_pointer){
        int socket = *(int *) socket_pointer;
        char buffer[1024];
        sprintf(buffer,"Hello There\n");
        write(socket,buffer,1024);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多