Send a file over TCP

Source: Internet
Author: User
Tags socket error
// File Transfer thread // the server sends a file. The client sends the file message uint threadsendfile (lpvoid pvar) {cdlgsendmessage * pdlg = (cdlgsendmessage *) pvar; cfile m_fsendfile; m_fsendfile.close (); if (! M_fsendfile.open (pdlg-> m_sendfilepath, cfile: moderead | cfile: typebinary) {afxmessagebox ("failed to open the file! "); Return false;} socket ssendmsg; // client socket sockaddr_in inetaddr; ssendmsg = socket (af_inet, sock_stream, ipproto_ip); If (invalid_socket = ssendmsg) {afxmessagebox ("An error occurred while creating the client to send the socket! "); M_fsendfile.close (); Return 0;} inetaddr. sin_family = af_inet; inetaddr. sin_port = htons (pub_msg_port); inetaddr. response = inet_addr (pdlg-> m_receiveip); // If (socket_error = connect (ssendmsg, (sockaddr *) & inetaddr, sizeof (sockaddr_in ))) // It is the recipient of the file {afxmessagebox ("the recipient is not online. listening socket does not exist. failed! "); Closesocket (ssendmsg); m_fsendfile.close (); Return 0 ;}char buff [max_buf_size] =" "; cstring strmsgsend (" 1001/"); cstring strsize; // calculate the file size if (pdlg-> m_fisendfile.nfilesizelow/(1024*1024 )! = 0) {strsize. format ("%. 2fmb ", pdlg-> m_fisendfile.nfilesizelow/(1024.0*1024);} else {strsize. format ("%. 2fkb ", pdlg-> Bytes/(1024.0);} memcpy (buff, pdlg-> m_fisendfile.szfiletitle, sizeof (pdlg-> m_fisendfile.szfiletitle); strmsgsend + = Buff; strmsgsend + = "/"; strmsgsend + = strsize; strmsgsend + = "/"; // send the file title, file Size // send messages as a client and accept socket If (socket_error = Send (ssendmsg, strmsgsend. getbu Ffer (0), strmsgsend. getlength (), 0) {afxmessagebox ("message sending failed!: Threadsendfile "); closesocket (ssendmsg); m_fsendfile.close (); Return 0;} memset (buff, 0, max_buf_size); If (socket_error = Recv (ssendmsg, buff, max_buf_size, 0) // receives the feedback from the other party // receives the consent acceptance message {afxmessagebox ("failed to receive the message!: Threadsendfile "); closesocket (ssendmsg); m_fsendfile.close (); Return 0 ;}// parse the recipient's confirmation information cstring strcmd; strcmd + = Buff; strcmd = strcmd. left (4); int icmd =-1; icmd = atoi (strcmd); If (msg_accept! = Icmd) {afxmessagebox ("the recipient rejects receiving files!: Threadsendfile "); closesocket (ssendmsg); m_fsendfile.close (); Return false; /// the other party agrees to receive the file and starts sending the file. // create a server sending file socket, open file_portsocket ssendfile; // listen to Socket socket saccept; // send and accept socket sockaddr_in accept; ACCEPT; ssendfile = socket (af_inet, sock_stream, ipproto_ip); If (invalid_socket = ssendfile) {afxmessagebox ("An error occurred while creating the socket!: Threadsendfile "); closesocket (ssendmsg); m_fsendfile.close (); Return 0;} inetaddrsendfile. sin_addr.s_addr = htonl (inaddr_any); inetaddrsendfile. sin_port = htons (pub_file_port); inetaddrsendfile. sin_family = af_inet; If (socket_error = BIND (ssendfile, (sockaddr *) & inetaddrsendfile, sizeof (sockaddr) {afxmessagebox ("A socket binding error!: Threadsendfile "); closesocket (ssendmsg); closesocket (ssendfile); m_fsendfile.close (); Return 0 ;}if (socket_error = listen (ssendfile, 5 )) {afxmessagebox ("listener error!: Threadsendfile "); closesocket (ssendmsg); closesocket (ssendfile); m_fsendfile.close (); Return 0 ;}int ilen = sizeof (sockaddr); saccept = accept (ssendfile, (sockaddr *) & inetaddraccept, & ilen); If (invalid_socket = saccept) {afxmessagebox ("Accept socket error occurred!: Threadsendfile "); closesocket (ssendmsg); closesocket (ssendfile); m_fsendfile.close (); Return 0 ;}// send file information to the recipient char buffinfo [max_buf_size] = ""; memcpy (buffinfo, & pdlg-> m_fisendfile, sizeof (pdlg-> m_fisendfile); send (saccept, buffinfo, sizeof (pdlg-> m_fisendfile), 0); memset (buffinfo, 0, max_buf_size); // the other party agrees to receive huozebujieshou and start to transmit Recv (saccept, buffinfo, max_buf_size, 0 ); // if the recipient does not keep it, do not go down. // send the file DWORD dwread cyclically = 0; DWORD dwcurrentread = 0; byte * breadbuff = new byte [max_buf_size]; // set sending progress while (dwread <pdlg-> m_fisendfile.nfilesizelow) {dwcurrentread = 0; memset (breadbuff, 0, max_buf_size); dwcurrentread = m_fsendfile.read (breadbuff, max_buf_size); // read data to the buffer if (socket_error = Send (saccept, (char *) breadbuff, dwcurrentread, 0 )) // send data {afxmessagebox ("File Sending interrupted!: Threadsendfile "); // if the recipient cancels the operation, the sender also keeps following closesocket (ssendmsg); closesocket (ssendfile); m_fsendfile.close (); break;} dwread + = dwcurrentread; // The data has been sent cstring STR; Str. format ("% d", dwread); afxmessagebox ("sent" + Str);} afxmessagebox ("sent"); Delete breadbuff; // release heap memory // process m_fsendfile.close () at the end; // close if (invalid_socket! = Saccept) {closesocket (saccept); // close accept socket} If (invalid_socket! = Ssendfile) {closesocket (ssendfile); // close the sending socket} afxendthread (0); return 1 ;}// the client file receiving thread uint threadrecvfile (lpvoid pvar) {char * m_sip = (char *) pvar; socket sfilerecv; sockaddr_in inetaddr; // create a new client socket and connect to the file sender server to receive the file sfilerecv = socket (af_inet, sock_stream, ipproto_ip); If (invalid_socket = sfilerecv) {afxmessagebox ("failed to create socket: threadrecvfile"); afxendthread (0); Return 0;} inetaddr. sin_family = af_inet; Inetaddr. sin_port = htons (pub_file_port); inetaddr. sin_addr.s_addr = inet_addr (m_sip); If (socket_error = connect (sfilerecv, (sockaddr *) & inetaddr, sizeof (sockaddr ))) // connect to the server IP {afxmessagebox ("connection to the target host error: threadrecvfile"); closesocket (sfilerecv); afxendthread (0); Return 0 ;}// receive file information fileinfo firecvfile; if (socket_error = Recv (sfilerecv, (char *) & firecvfile, sizeof (fileinfo), 0) {afxmessagebox ("receives File Information Error: threadrecvfile "); closesocket (sfilerecv); afxendthread (0); Return 0;} cstring strfileinfo; double nfilesize = 0.0; If (firecvfile. nfilesizelow/(1024*1024 )! = 0) {nfilesize = firecvfile. nfilesizelow/(1024*1024); strfileinfo. format ("receiving file... \ n from [% s], \ n file name [% s] size: [%. 2f] MB ", inet_ntoa (inetaddr. sin_addr), firecvfile. szfiletitle, nfilesize);} else {nfilesize = firecvfile. nfilesizelow/(1024); strfileinfo. format ("receiving file... \ n from [% s], \ n file name [% s] size: [%. 2f] kb ", inet_ntoa (inetaddr. sin_addr), firecvfile. szfiletitle, nfilesize);} cfiledialog fdlgsave (false, nu Ll, firecvfile. szfiletitle, ofn_hidereadonly | ofn_overwriteprompt, _ T ("All (*. *) | *. * | "); char buff [max_buf_size] =" "; cacmoduleresourceoverride thisresource; If (fdlgsave. domodal ()! = Idok) {sprintf (buff, "% d", msg_reject); send (sfilerecv, buff, sizeof (buff), 0); closesocket (sfilerecv ); // cause afxendthread (0) in the middle of the sending file;} cstring strfilepath; strfilepath = fdlgsave. getpathname (); cfile frecvedfile (strfilepath, cfile: modecreate | cfile: modewrite | cfile: typebinary); DWORD dwtotalread; DWORD dwcurrentread; dwtotalread = 0; // total received byte dwcurrentread = 0; // The received byte * databuff = new byte [max_buf _ SIZE]; // allocate heap memory buffer // start to receive memset (buff, 0, sizeof (buff); sprintf (buff, "% d", msg_begin ); send (sfilerecv, buff, sizeof (buff), 0); While (dwtotalread <firecvfile. nfilesizelow) {dwcurrentread = 0; memset (databuff, 0, max_buf_size); dwcurrentread = Recv (sfilerecv, (char *) databuff, max_buf_size, 0 ); if (0 = dwcurrentread | socket_error = dwcurrentread) {cstring strfilerecvinfo; strfilerecvinfo. format (" Failed to receive: % s! ", Firecvfile. szfiletitle); break;} frecvedfile. write (databuff, dwcurrentread); dwtotalread + = dwcurrentread; // cstring STR; // Str. format ("% d", dwtotalread); // afxmessagebox ("accepted" + Str); double icompleted = 0.0; icompleted = (dwtotalread * 1.0)/firecvfile. nfilesizelow; icompleted* = 10.0; cstring strsavedinfo; strsavedinfo. format ("% d", icompleted);} Delete databuff; // release the heap memory cstring strfilerecvinfo; Strfilerecvinfo. Format ("Received: % s complete! ", Firecvfile. szfiletitle); afxmessagebox (strfilerecvinfo); If (sfilerecv! = Invalid_socket) {closesocket (sfilerecv);} // close the file frecvedfile. close (); // clear the file information // memset (& pdlg-> m_fisendfile, 0, sizeof (pdlg-> m_fisendfile); // afxendthread (0 ); return 1;} // Service Listening thread // establish the server model uint threadserver (lpvoid pvar) {sockaddr_in inetaddr; sockaddr_in inetaccept; socket saccept; socket mysock; // The server listening socket mysock; mysock = socket (af_inet, sock_stream, ipproto_ip); If (invalid_socket = mysock) {afxmessagebo X ("socket creation failed! "); Return false;} inetaddr. sin_family = af_inet; inetaddr. sin_port = htons (pub_msg_port); // message listening port // inetaddr. sin_port = 0; inetaddr. dependencies = htonl (inaddr_any); // bind if (invalid_socket = BIND (mysock, (sockaddr *) & inetaddr, sizeof (sockaddr) {afxmessagebox ("socket binding error: threadserver! "); Closesocket (mysock); Return 0 ;}// listen to If (0! = Listen (mysock, 5) {afxmessagebox ("socket listening error: threadserver! "); Return 0;} // afxmessagebox (" Message Service started successfully "); // acceptint ilen = sizeof (sockaddr_in); While (true) {// server session socket saccept = accept (mysock, (sockaddr *) & inetaccept, & ilen); If (invalid_socket = saccept) {afxmessagebox ("failed to accept socket: threadserver! "); Return 0;} // start the message processing thread to process new messages // allocate heap memory and store the customer's socket information socketinfo * psinfo = new socketinfo; memset (psinfo, 0, sizeof (socketinfo); psinfo-> snow = saccept; psinfo-> inetaddr = inetaccept; // The client address afxbeginthread (threadrecvmsg, (lpvoid) psinfo );} // whilereturn 1;} // The server processes the message processing thread. After the new message arrives, it starts. After the processing is complete, the uint threadrecvmsg (lpvoid pvar) {socketinfo * psockinfo = (socketinfo *) pvar is disabled; socketinfo sockinfo = * psockinfo; Dele Te psockinfo; // release heap memory // each thread has a separate memory, which must be released for reference. In fact, the sub-thread steals the memory of the parent thread int irecv =-1; char buff [max_buf_size] = ""; char szmsg [256] = ""; // start to receive messages irecv = Recv (sockinfo. snow, buff, sizeof (buff), 0); // If (socket_error = irecv) {closesocket (sockinfo. snow); afxmessagebox ("An error occurred while receiving the message!: Threadrecvmsg "); afxendthread (0);} // 1001/storm sound 2007.exe/32 MB/strcpy (szmsg, buff); int itype = 0; cstring strtemp; cstring strinmsg; strtemp + = szmsg; strinmsg + = szmsg; strtemp = strtemp. left (4); itype = atoi (strtemp); // determine whether the message is received by the file if (msg_new_file = itype) {cstring strmsginfo; cstring strhost; cstring strfilename; cstring strsize; int I, j; I = 0; j = 0; I = strinmsg. find ("/"); j = strinmsg. find ("/", I + 1); // obtain the file name strfilename = strinmsg. mid (I + 1, J-I-1); strinmsg. trimright ("/"); // obtain the file size strsize = strinmsg. right (strinmsg. getlength ()-strinmsg. reversefind ('/')-1); strmsginfo. format ("[File Source: % s] \ n [File Name: % s] \ n [file size: % s]", inet_ntoa (sockinfo. inetaddr. sin_addr), strfilename, strsize); strmsginfo + = "\ n agree to receive it? "; Cacmoduleresourceoverride thisresource; If (idyes = MessageBox (null, strmsginfo," New message ", mb_yesno) {char buffsend [max_buf_size] = ""; char sztemp [20] = ""; ITOA (msg_accept, sztemp, 10); strcpy (buffsend, sztemp ); // send the consent message to the recipient if (socket_error = Send (sockinfo. snow, buffsend, sizeof (buffsend), 0) {afxmessagebox ("failed to send message: threadrecvmsg"); closesocket (sockinfo. snow); afxendthread (0);} // If char * senderip; senderip = inet_ntoa (sockinfo. inetaddr. sin_addr); // start the file receiving thread afxbeginthread (threadrecvfile, (lpvoid) senderip);} // If else {char buffsend [max_buf_size] = ""; char sztemp [20] = ""; ITOA (msg_reject, sztemp, 10); strcpy (buffsend, sztemp ); // send a reject message to the recipient if (socket_error = Send (sockinfo. snow, buffsend, sizeof (buffsend), 0) {afxmessagebox ("failed to send message: threadrecvmsg"); closesocket (sockinfo. snow); afxendthread (0);} // If} // else} // ifelse {afxmessagebox ("unidentifiable message");} // elsereturn 0 ;}

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.