c - Unable to connect with multiple client with my socket server program -
my socket server program mentioned below. works fine single client when try connect client @ same time, unable connect. have defined max_clients in program 2 still why unable connect multiple clients? correct process connect multiple client? able connect multiple client modifying code? possible fix?
socket server code:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <error.h> #include <strings.h> #include <unistd.h> #include <arpa/inet.h> #define error -1 #define max_clients 2 #define max_data 1024 main (int argc, char **argv){ struct sockaddr_in server; struct sockaddr_in client; int sock; int new; int sockaddr_len = sizeof (struct sockaddr_in); int data_len; char data [max_data]; if ((sock = socket (af_inet, sock_stream, 0)) == -1) { perror ("socket: "); exit (-1); } printf("after socket"); server.sin_family = af_inet; server.sin_port = htons(atoi(argv[2])); server.sin_addr.s_addr = inaddr_any; bzero (&server.sin_zero, 8); printf("after server"); if ((bind (sock, (struct sockaddr*)&server, sockaddr_len)) == -1) { perror ("bind"); exit (-1); } printf("after bind"); if ((listen(sock, max_clients)) == error) { perror ("listen"); exit (-1); } printf("after listen"); while(1) { if ((new = accept(sock, (struct sockaddr*)&client, &sockaddr_len)) == error) { perror ("accept"); exit (-1); } printf("after new"); printf("new client connected port no %d , ip %s\n",ntohs(client.sin_port), inet_ntoa(client.sin_addr)); data_len = 1; while (data_len) { data_len = recv (new, data, max_data, 0); if (data_len) { send (new, data, data_len, 0) ; data [data_len]='\0'; printf("sent mesg: %s", data); } printf("after datalen"); } printf("client disconnected\n"); close(new); } printf("after close new"); close (sock); }
your program single-threaded, , 1 thing @ time. when have accepted socket connection client (in outer while loop) start communicating client (in inner while loop), , don't accept call until first client has disconnected.
either use threads, 1 thread waits new connections , 1 additional thread each client, waiting input client, or use select call, lets wait input simultaneously several different sources.
Comments
Post a Comment