Implementation of the socket file transfer function

Source: Internet
Author: User
Tags htons

Service side:

#include  <stdio.h> #include  <winsock2.h> #pragma  comment  (lib,  "Ws2_32.lib" )   //load  ws2_32.dll   #define &NBSP;BUF_SIZE&NBSP;1024&NBSP;&NBSP;INT&NBSP;MAIN (int  argc, char *argv[] {    //First check if the file exists     char * filename =  "Beyond.mp3";//File name     file *fp = fopen (filename,  "RB");//Open file in binary mode     if (fp == null)     {         printf ("cannot open file, press any key to  Exit!\n ");         system (" Pause ");         exit (0);     }         //initialization   Dll    wsadata wsadata;    wsastartup ( MAKEWORD (2,&NBSP;2),  &wsadata);        //Create Socket     socket servsock = socket ( PF_INET,&NBSP;SOCK_STREAM,&NBSP;IPPROTO_TCP);     if (Servsock == invalid_socket)     {        printf ("Failed socket (). \ n");         wsacleanup ();         return 0;    }       //binding Sockets      struct sockaddr_in sockaddr;    memset (&sockaddr, 0, sizeof ( SOCKADDR))   //each byte is filled with 0     sockAddr.sin_family = PF_INET;   Use IPV4 address     sockaddr.sin_addr.s_addr = inet_addr ("127.0.0.1");   // Specific IP address     sockaddr.sin_port = htons (1234);   //Port      if (Bind (servsock,  (sockaddr*) &sockaddr, sizeof (sockaddr))  == socket_error)     {         printf ("Failed bind (). \ n");         wsacleanup ();        return 0;     }       //into the Listening state     listen (servSock,         //loop receive client request     int nSize =  sizeof (SOCKADDR);     char buffer[buf_size] = {0};//Buffer       SOCKADDR clntAddr;    SOCKET clntSock;            for (;;)     {        clntsock = accept (ServSock,   (sockaddr*) &clntaddr, &nsize);        &nBsp;if (Clntsock == invalid_socket)         {             printf ("failed accept (). \ n");             continue;         }            int nCount;         while (Ncount = fread (buffer, 1, buf_size,  FP)  > 0)         {             send (clntsock, buffer, ncount, 0);//cycle data until end of file           }        shutdown ( Clntsock, sd_send)///file read, disconnect the output stream, send fin packets to the client                    recv (clntsock, buffer, buf_size, 0);//blocking, waiting for the client to receive the completion                              memset (buffer, 0, buf_size);//Set Buffer                   fclose (FP);         closesocket (clntsock);     }       //Close socket      closesocket (servsock);        //termination  DLL  use      wsacleanup ();         system ("Pause");     return 0;}




Client:

#include  <stdio.h> #include  <stdlib.h> #include  <winsock2.h> #pragma   Comment (lib,  "ws2_32.lib")   #define  buf_size 1024  int main (INT&NBSP;ARGC,  char *agrv[] {    //Enter the filename first to see if the file can be created successfully     char filename [100] = {0}; //filename     printf ("input filename to save: " );     gets (filename);     file *fp = fopen (filename,   "WB");//open (Create) file in binary mode     if (fp == null)     {         printf ("Cannot open file, press any key  to exit!\n ");         system (" Pause ");         exit (0);    }         //Initialize dll    Wsadata wsadata;    wsastartup (Makeword (2,2),  &wsadata);           //Create Socket     socket sock = socket ( PF_INET,&NBSP;SOCK_STREAM,&NBSP;IPPROTO_TCP);     if (Sock == invalid_socket)     {        printf ("Failed socket (). \ n");         wsacleanup ();         return 0;    }           // Initiating a request to the server     struct sockaddr_in sockaddr;    memset (& Sockaddr, 0, sizeof (sockaddr))  //each byte is filled with 0     sockaddr.sin_family = &NBSP;PF_INET;&NBSP;&NBSP;&NBSP;&NBSP;SOCKADDR.SIN_ADDR.S_ADDR&NBSP;=&NBSP;INET_ADDR ("127.0.0.1");     sockaddr.sin_port&nBsp;= htons (1234);     if (Connect (sock,  (sockaddr*) &sockaddr, sizeof ( SOCKADDR)  == -1)     {        printf (" Failed connect (). \ n ");         wsacleanup ();         return 0;    }            //Loop accepts data and knows file transfer is complete      char buffer[buf_size] =  {0}; //file buffer      int ncount;    while (nCount &NBSP;=&NBSP;RECV (sock, buffer, buf_size, 0))  > 0)     {         fwrite (BUFFER,&NBSP;NCOUNT,&NBSP;1,&NBSP;FP);     }    puts ("file transfer success!\n");            &nbsP;memset (buffer, 0, buf_size);//Reset Buffer                fclose (FP);     closesocket (sock);            //termination using Dll    wsacleanup ();         system ("pause");     return 0; }


Implementation of the socket file transfer function

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.