Linux network programming 6--using TCP to implement file servers

Source: Internet
Author: User
Tags server port htons

Demand

When the client connects to the server, the server transfers the file to the client and implements the file download.

Ideas

Server-side, the main process is responsible for listen. Within the loop, the main process will fork out the grandson to complete the file transfer every request from the task request queue. Note: If you just fork out the son, then the main process will have to wait for the son, so that only after the file is sent to a client to the next.

Code

Server Side

/************************************************************************* > File name:server.c > Author: Krischou > Mail:[email protected] > Created time:thu 09:40:32 PM CST ******************************* *****************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<unistd.h>#include<netdb.h>#defineSndsize 1024*1024//1M, note that if the stack space (can be set) is not so large, use the heap space#definefile_name "A.RMVB"intMainintargcChar* argv[])//exe config{    /*To read the server from the configuration file contact: IP and port number*/    intfd_conf; Fd_conf= Open (argv[1], o_rdonly); FILE* fp_conf = Fdopen (fd_conf,"R");//show me. Fdopen function, file descriptor converted to file pointer fdopen (int fd, const char *mode)    Charmy_ip[ +]=""; intMy_port; FSCANF (fp_conf,"%s%d", My_ip, &my_port);    Close (fd_conf);    Fclose (fp_conf); /*Create a listener socket port for the server*/    intFd_listen Fd_listen= Socket (Af_inet, Sock_stream,0); if(Fd_listen = =-1) {perror ("Socket"); }    /*bind the server socket port to connect to the client*/        structsockaddr_in server_addr; memset (&AMP;SERVER_ADDR,0,sizeof(SERVER_ADDR)); Server_addr.sin_family=af_inet; Server_addr.sin_port=htons (My_port); Server_addr.sin_addr.s_addr=inet_addr (MY_IP); if(-1= = Bind (Fd_listen, (structSOCKADDR *) &server_addr,sizeof(SERVER_ADDR))) {Perror ("Bind");        Close (Fd_listen); Exit (1); }    /*Listen*/    if(-1= = Listen (Fd_listen,5) {perror ("Listen");        Close (Fd_listen); Exit (1); }        /*Accept*/    intFd_client;/*the other end of the client socket port*/    structSockaddr_in client_addr;/*Client Contact method, given the outgoing parameters of the Accept function*/    intLen; memset (&AMP;CLIENT_ADDR,0,sizeof(CLIENT_ADDR)); Len=sizeof(CLIENT_ADDR);  while(1) {fd_client= Accept (Fd_listen, (structSOCKADDR *) &client_addr, &Len); if(Fd_client = =-1)         {            Continue ; } printf ("a client connect! ip:port%s:%d\n", Inet_ntoa (CLIENT_ADDR.SIN_ADDR), Ntohs (Client_addr.sin_port)); if(fork () = =0) {close (Fd_listen);//The listen port is not required for child processes and grandchildren processes and is closed directly.             if(fork () = =0)            {                intFd_file = open (file_name, o_rdonly);//Open the file that the client wants to download                CharBuf[sndsize]; intsnd_cnt =0 ; intReadn; /*read data from a file and send it to the client*/                 while(Memset (BUF,0, Sndsize), (Readn = Read (Fd_file,buf, sndsize)) >0)                {                        if(Send (Fd_client, buf, READN,0) !=Readn) {printf ("send error! \ n"); } snd_cnt++ ; } printf ("send over:%d \ n", snd_cnt);                Close (Fd_file);                Close (fd_client); Exit (0);            } close (fd_client); Exit (0);        } close (fd_client);    Wait (NULL); }    return 0 ;}

Client Side

/************************************************************************* > File name:client.c > Author:k Rischou > Mail:[email protected] > Created time:thu 11:59:20 PM CST **************************** ********************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<unistd.h>#include<netdb.h>#defineSndsize 1024*1024#defineServer_port 6080//Server PortintMainintargcChar*argv[]) EXE ip{/*Socket*/    intfd_client; Fd_client= Socket (Af_inet, Sock_stream,0); if(Fd_client = =-1) {perror ("Socket"); Exit (1); }    /*structure that holds information about the attached server*/    structsockaddr_in server_addr; memset (&AMP;SERVER_ADDR,0,sizeof(SERVER_ADDR)); Server_addr.sin_family=af_inet; Server_addr.sin_port=htons (Server_port); Server_addr.sin_addr.s_addr= Inet_addr (argv[1]); /*Connect*/     while(Connect (Fd_client,structSOCKADDR *) &server_addr,sizeof(SERVER_ADDR)) == -1)    {        /*when Connect returns 1, the server is not started*/Sleep (1); printf ("connecting ... \ n"); } printf ("connect success! \ n"); intFd_write = open ("txt", O_wronly | O_creat);//the downloaded content is written to the local file    CharBuf[sndsize]; intReadn; intrecv_cnt =0;  while(Memset (BUF,0, Sndsize), (Readn = recv (Fd_client,buf,sndsize,0)) >0) {write (FD_WRITE,BUF,READN); Recv_cnt++; } printf ("recv over:%d \ n", recv_cnt);    Close (Fd_write);    Close (fd_client); return 0;}

Linux network programming 6--using TCP to implement file servers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.