I'm creating a client-server chat program in C using sockets and threads and having an issue implementing multi-threading. What I have currently got is a server that takes connections from clients using sockets that is working so far, the issue is when I try create multiple threads to handle sending and receiving.
When a client successfully connects to the server socket a thread is created in the client that handles receiving a message 'connected to server id: x', before it reaches the main while loop of the client program.
When a client reaches the server, a thread is created in the server to handle sending that data.
They seem to work okay but its the order of execution that is getting me. When I connect the client to the server what I thought would happen was the thread created to receive a message from the server would execute then the main while loop would. But instead it looks like the thread is waiting for main loop to take input.
// CURRENT CLIENT CODE - only including threading code
void * client_receive(void * sockID) {
int network_socket = *((int *) sockID);
while(1) {
char data[1024];
recv(network_socket, data, 1024, 0);
printf("%s", data);
}
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, client_receive, (void *) &network_socket);
while(1) {
printf("type a message: ");
scanf("%s", message);
send(network_socket, message, 1024, 0);
}
}
________________________________________________________________________________
// CURRENT SERVER CODE
struct client {
int index;
int sockID;
struct sockaddr_in clientAddr;
int len;
};
void * client_interact(void * client_detail) {
struct client* client_Detail = (struct client*) client_detail;
int index = client_Detail -> index;
int clientSocket = client_Detail -> sockID;
index = index + 1;
printf("Client connected");
char message[1024] = "Welcome!";
send(clientSocket, message, 1024, 0);
while(1) {
char receive[1024];
recv(clientSocket, &receive, 1024, 0);
printf("Client: %s", receive);
}
}
struct client Client[1024];
pthread_t thread[1024];
int main() {
while(1) {
pthread_create(&thread[client_count], NULL, client_interact, (void *) &Client[client_count]);
client_count++;
}
for (int i = 0; i < client_count; i++) {
pthread_join(thread[i], NULL);
}
return 0;
}
Am I misunderstanding execution of threads? I thought that 'client_receive' would execute on the created thread before main printed 'type a message'