无法读取服务器发送的消息

时间:2017-05-06 09:51:05

标签: c multithreading tcp client-server ipc

我有服务器客户端连接,我正在尝试读取服务器发送的消息。我在main函数中使用的代码有效,但是当我尝试读取线程中的消息时,它不会读取任何内容。这是我正在使用的代码:

newsockfd = connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

sock_desc = malloc(1);
*sock_desc = newsockfd; 

//create a new thread
pthread_t client_thread;
if(pthread_create(&client_thread, NULL, thread_function, (void *)sock_desc)<0)
     error("ERROR creating thread!");

//thread function
void *thread_function(void * sock_desc){

//get the socket descriptor
int sock = *(int*)sock_desc;
printf("sock %d\n", sock);
int n;

printf("New thread\n");
fflush(stdout);

bzero(buffer,256);
n = read(sock,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);

return (void *)0;

}//close thread_function()

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

正如评论中所指出的,您的分配是错误的,但

    newsockfd = connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

问题。 connect不会返回新套接字。它返回成功/失败状态。你应该

    if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        handle_connection_error();
    } else {
        pthread_create(&client_thread, NULL, thread_function, (void *)&sockfd);
    }