Hello all,
I have in mind the creation of a chat server to test how do the sockets work.
I created a simple server which attends 1 client at a time and then closes the connection.
Now I would need to know how to store that client sockets into an array so I can later make them to communicate between them using the file descriptor creating a child process for each one.
I got this code so far:
I would appreciate any help about how to do it.Code:// Standard libs #include <stdio.h> // Socket related libs #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 4000 #define CLIENTS 2 int main(void) { // File descriptors for client and server int socketServer; int socketClient; struct sockaddr_in server; struct sockaddr_in client; int sin_size; print_info(); printf("Initializing server...\n"); printf("Creating sockets... "); if((socketServer=socket(AF_INET, SOCK_STREAM, 0)) == -1){ printf("[FAILED]\n"); perror("Initializing socket()"); return 1; } else printf("[OK]\n"); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; bzero(&(server.sin_zero),8); printf("Binding sockets... "); if(bind(socketServer,(struct sockaddr*)&server, sizeof(struct sockaddr))==-1) { printf("[FAILED]\n"); perror("bind()"); return 1; } else printf("[OK]\n"); printf("Listening on port %d... ",PORT); if(listen(socketServer,CLIENTS) == -1) { printf("[FAILED]\n"); perror("listen()"); return 1; } else printf("[OK]\n"); // Continuously accepting remote connections while(1){ sin_size=sizeof(struct sockaddr_in); if ((socketClient = accept(socketServer,(struct sockaddr *)&client, &sin_size))==-1) { perror("accept()"); return 1; } printf("Connection accepted from %s\n", inet_ntoa(client.sin_addr) ); printf("Sending welcome message...\n"); send(socketClient,"Welcome to my server\n",22,0); printf("Closing client connection\n"); close(socketClient); } close(socketServer); return 0; }
Regards,
Ernie-



2Likes
LinkBack URL
About LinkBacks





