After a little change, make a little change to the example of the previous foundation.
Concurrent server, the Server fork () a new child process per request.
Compile and run the method in the previous article.
/*client_tcp.c*/#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<netinet/inch.h>#defineMAXLINE 4096#definePORT 12345voidProcess (FILE *FP,intsockfd) { CharSend[maxline], recv[maxline]; while(Fgets (send, MAXLINE, fp)! =NULL) {Write (SOCKFD, send, strlen (send)); intn =Read (SOCKFD, recv, MAXLINE); Recv[n]=0; Fputs (recv, stdout); }}intMainintargcChar*argv[]) { intSOCKFD, N; CharRecvline[maxline+1]; structsockaddr_in servaddr; if(ARGC! =2) {fprintf (stderr,"usage:client_tcp <ip>\n"); Exit (1); } if(SOCKFD = socket (af_inet, Sock_stream,0)) <0) {fprintf (stderr,"Socket error\n"); Exit (1); } bzero (&SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port=htons (PORT); if(Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <=0) {fprintf (stderr,"Inet_pton error for%s\n", argv[1]); Exit (1); } if(Connect (SOCKFD,structSOCKADDR *) &Servaddr,sizeof(SERVADDR)) <0) {fprintf (stderr,"Connect error\n"); Exit (1); } process (stdin, SOCKFD); Exit (0);}
/*server_tcp.c*/#include<stdlib.h>#include<string.h>#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<netinet/inch.h>#defineMAXLINE 4096#defineListenq 1024#definePORT 12345voidProcessintsockfd) {ssize_t n; CharBuff[maxline+1]; while((n = read (SOCKFD, buff, MAXLINE)) >0{write (SOCKFD, buff, n); }}intMainintargcChar*argv[]) { intLISTENFD, CONNFD; structsockaddr_in servaddr, cliaddr; pid_t pid; LISTENFD= Socket (Af_inet, Sock_stream,0); Bzero (&SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_addr.s_addr=htonl (Inaddr_any); Servaddr.sin_port=htons (PORT); Bind (LISTENFD, (structSOCKADDR *) &servaddr,sizeof(SERVADDR)); Listen (LISTENFD, Listenq); while(1) { intClilen =sizeof(CLIADDR); CONNFD= Accept (LISTENFD, (structSOCKADDR *) &cliaddr, &Clilen); if(PID = fork ()) = =0) {// ChildClose (LISTENFD); Process (CONNFD); Exit (0); } close (CONNFD); } exit (0);}
UNIX Network Programming TCP client server: concurrency, message echo