I. Summary
1. Big bag to send small bag, only once.
2. Send the file extension, file length is also sent together, convenient to receive the receiver to save as the correct file type, and determine whether it has been received.
If not sent together, divided into file extension, file length, file content, sent three times, at the receiving end, may also be received, but not conducive to parsing.
Two. Customer send-side code
Private voidBtnsend_click (Objectsender, EventArgs e) { //assemble a remote endpointIPAddress IPAddress = Ipaddress.parse ( This. Txtip3.text); IPEndPoint Hostep=NewIPEndPoint (IpAddress, Convert.ToInt32 ( This. Txtport3.text)); Socket Socket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Try{socket. Connect (Hostep); //1. Send User Agreement stringpath1 = environment.currentdirectory;//gets the current working directory of the application. stringDoc ="yoursendfile.pdf"; stringPath =Path.Combine (path1, doc); FileStream FS=File.Open (path, FileMode.Open); //File Contents byte[] Bdata =New byte[FS. Length]; Fs. Read (Bdata,0, Bdata. Length); Fs. Close (); //file extension, fixed 3 bytes byte[] Fileextarray = Encoding.UTF8.GetBytes (string. Format ("{0:D3}", Currentdocext)); //file length, fixed to 20 bytes, preceded by auto-fill 0 byte[] Filelengtharray = Encoding.UTF8.GetBytes (bdata. Length.tostring ("D20")); //Merging byte arrays byte[] Filearray =Combombinaryarray (Fileextarray, Filelengtharray); //Merging byte arrays byte[] Bdata1 =Combombinaryarray (Filearray, bdata); //Send file length + file contentSocket. Send (Bdata1, bdata1. Length,0); //2. Receiving//declares a string that receives the returned content stringRecvstr =""; //declares an array of bytes, with a length of 1024 bytes of data received at a time byte[] Recvbytes =New byte[1024x768]; //returns the number of bytes actually received intbytes =0; //Loop read until all data is received while(true) {bytes= socket. Receive (Recvbytes, Recvbytes.length,0); //exit loop When read is complete if(Bytes <=0) Break; //converts the number of bytes read to a stringRecvstr + = Encoding.UTF8.GetString (Recvbytes,0, bytes); } //Disable Socketsocket. Shutdown (Socketshutdown.both); //Close Socketsocket. Close (); //... do some busness logic ... } Catch(Exception E1) {ThrowE1; } }
Three. Service Receive-side code
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net.Sockets;usingSystem.Net;usingSystem.Xml;usingSystem.Configuration;usingSystem.Windows.Forms;usingSystem.IO;namespaceconsoleappserver{classProgram {[STAThread]Static voidMain (string[] args) { BOOLDone =false; IPAddress IPAddress= Ipaddress.parse (configurationsettings.appsettings["IP"]. ToString ()); IPEndPoint Hostep=NewIPEndPoint (IpAddress, Convert.ToInt32 (configurationsettings.appsettings["Port"])); Socket Socket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Socket. Bind (Hostep); Socket. Listen (3); while(!Done ) {Console.WriteLine ("Waiting for client"); Socket Client=socket. Accept (); Console.WriteLine ("Connected Client"); //1. Receiving//declares an array of bytes, with a length of 1024 bytes of data received at a time byte[] Recvbytes =New byte[1024x768]; //returns the number of bytes actually received intbytes =0; intFilelength =0;//900866; intReceivedlength =0; //1.0 receive file name extensionsbytes = client. Receive (Recvbytes,3,0); stringFileext = Encoding.UTF8.GetString (Recvbytes,0, bytes); stringVfilepath =environment.currentdirectory; stringVfilename = Vfilepath +"\\TMP"+ Guid.NewGuid (). ToString () +"."+Fileext; //Create a file stream, and then let the file stream create a file based on the pathFileStream fs =NewFileStream (Vfilename, FileMode.Create); //1.1 Receive file lengthbytes = client. Receive (Recvbytes, -,0); //converts the number of bytes read to a string stringFilelength = Encoding.UTF8.GetString (Recvbytes,0, bytes); Filelength=Convert.ToInt32 (filelength); //1.2 Receiving file Contents while(Receivedlength <filelength) {bytes= client. Receive (Recvbytes, Recvbytes.length,0); Receivedlength+=bytes; Fs. Write (Recvbytes,0, bytes); } fs. Flush (); Fs. Close (); //... does some business logic ... stringReturndata =somebusinesslogic (); //2. Send byte[] Bdata =Encoding.UTF8.GetBytes (returndata); Client. Send (Bdata, Bdata. Length,0); Client. Close (); } socket. Shutdown (Socketshutdown.both); Socket. Close (); } }}
How do I send and receive a file via socket TCP?