I am programming a internet chat program.
I am not sure how to implement "multiple chat rooms with multiple users". I have a few ideas but I'm not sure what is the best solution or proper way to do this, as I am a low-medium level C/Socket programmer. This is a simple project for learning, I don't want to try to implement thread pools or something complicated for now.
First implementation idea is to have multiple sockets listening on different ports OR should it be one socket listening on multiple ports?
- each group of clients will have their own port (or chat room)
- In my server driver , I will run/create a thread for each of those sockets? so that they can sit in a while loop and wait for client connections to accept()
- Then each socket thread will create a thread for each client connection? so that they can send back the chat room messages.
Ive quickly typed up some code, but I don't want to continue with this approach unless its correct...
Code:
server_drive.c
int ports[3] = {3000,5000,8000};
for(int i=0; i < 3; i++){
chat_room_sockets[i] = new_chat_room_socket(ports[i]);
pthread_t thread;
int* sock = malloc(sizeof(int));
*sock = chat_room_sockets[i];
pthread_create(&thread,NULL, start_chat_room, sock);
pthread_detatch(thread);
}
..
Code:
server_interface.h
int new_chat_room_socket(int port){
int server_sock;
struct sockaddr_in server_address;
if((server_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
return -1;
}
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(port);
if (bind(server_sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0){
return -1;
}
if (listen(server_sock, MAXPENDING) < 0){
return -1;
}
return server_sock;
}
void* start_chat_room(void* sock){
int client_sock;
struct sockaddr_in client_address;
int client_length = sizeof(client_address);
for(;;){
if((client_sock = accept((int)sock , (struct sockaddr*) &client_address , &client_length )) < 0){
//add_chat_user(client_sock);
}
}
..