套接字客户端/服务器聊天(线程问题)

时间:2014-03-13 10:43:22

标签: c sockets chat

我在实施客户端/服务器聊天时遇到问题。 问题是我无法同时处理与两个(或更多)客户端的连接。事实上,服务器只响应一个客户端,而不是全部响应。

服务器代码更像是这样:

/*include*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>

/*define*/
#define PORT 5050
#define MSG_SIZE 100
#define NUM_UTENTI 5 

//the thread function
void *fun_receiver(void *);
void *sender2(void *);

/*//////////////////////   MAIN FUNCTION  /////////////////////////////*/

int main(){


int serverfd , clientfd, c, *new_client;
struct sockaddr_in server_addr , client_addr;

//Create socket
serverfd = socket(AF_INET , SOCK_STREAM , 0);

//Prepare the sockaddr_in structure
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons( PORT );

//Bind
bind(serverfd,(struct sockaddr *)&server_addr , sizeof(server_addr));
puts("bind done");

//Listen
listen(serverfd , 5);

//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);

//thread_id
int t=0;
pthread_t thread_receiver;
pthread_t thread_invio;

while(true){
clientfd = accept(serverfd, (struct sockaddr *)&client_addr, (socklen_t*)&c);
if (clientfd < 0){
perror("accept failed");
return 1;}

new_client=malloc(sizeof(int));
*new_client=clientfd;


if( pthread_create( &thread_receiver , NULL , fun_receiver , (void*) new_client) < 0){
perror("could not create thread");
return 1;
}


if( pthread_create( &thread_invio , NULL , sender2 , (void*) new_client) < 0){
perror("could not create thread");
return 1;
}

}//end while

close(serverfd);
return 0;
} //fine main





//////sender
void *sender2(void *clientfd)
{
int sock = *(int*)clientfd;
char buf[30];

while(true){
bzero(&buf, 30 * sizeof(char));
printf("Inserisci Messaggio3: ");
gets(buf);
int len, byte_sent;
len=strlen(buf);
byte_sent = send(sock, buf, len, 0);
}

return 0;
}



////receiver
void *fun_receivervoid *serverfd)
{
int sock = *(int*)serverfd;

char msg[MSG_SIZE];
bzero(&msg, MSG_SIZE * sizeof(char));
int read_size;
int count = 0;


while( (read_size=recv(sock, msg, MSG_SIZE * sizeof(char), 0)) > 0 ){
/*if(strcmp(msg, exit)==0){
printf("Arrivederci!\n");
close(sock);
}*/
printf("%s\n", msg);
bzero(&msg, MSG_SIZE * sizeof(char));
}

return 0;
}

在connect()之后,相同的代码位于客户端:有两个线程用于发送消息(到服务器),另一个用于接收消息(来自服务器)。两个线程都依赖于相同的客户端套接字。

会发生什么:

client1连接到服务器(写入和接收来自服务器的消息)/ /一切都好!

client2连接到服务器(将消息写入服务器但没有收到任何内容......)

问题在于,如果服务器写入消息,则只有client1接收而client2不接收。

这怎么可能?哪里错了?我希望该服务器可以向所有客户端发送消息,而不仅仅是一个!

1 个答案:

答案 0 :(得分:0)

您的代码可以通过多种方式得到改进。但我觉得目前这里的关键问题是

 *new_client=clientfd;

指针(new_client)甚至没有初始化。而且你想要在多个线程中使用存储的值。 在这种情况下,您需要具有不同的内存区域,以便各个线程获得正确的连接描述符值。

我建议写

 new_client = malloc(sizeof(int));
 *new_client=clientfd;

现在各个线程将获得正确的连接描述符。我希望这能解决问题。

相关问题