[C # source code sharing] the client sends "small files" to the server through TCP communication,
Source code (excluding the source code of the communication framework, please download the source code of the communication framework separately)
In the previous article, I wrote how to send images to the client through TCP communication, and a friend asked me how to transfer files. This article will discuss how to send files.
For small files, you can convert the file into byte format and wrap it with the contract class. After the server receives the file, it can convert the byte into a file. This is also the implementation method in this article, the advantage of this method is that it is relatively simple and flexible. The disadvantage is that it is not suitable for sending large files or displaying the File Sending progress.
TCP-based communication mechanism. This method is not feasible for large files. It is better for large files to be sent and then merged in segments, we will discuss how to send large files in the future.
This program is based on the open-source networkComms2.3.1 communication framework.
Let's take a look at the implementation results.
Server:
Client:
On the server side, we save the received image in the root directory of drive D (you can specify another path). Open drive D and you will see the received image as follows:
The following describes the specific process.
Step 1: first set the server
(1) listening port:
// The server starts listening to client requests // starts listening to a T port IPEndPoint thePoint = new IPEndPoint (IPAddress. parse (txtIP. text), int. parse (txtPort. text); TCPConnection. startListening (thePoint, false); button1.Text = "listener"; button1.Enabled = false; // This method contains the specific server processing method. StartListening ();
(2) corresponding processing methods for file upload and write:
NetworkComms.AppendGlobalIncomingPacketHandler<FileWrapper>("UploadFile", IncomingUploadFile);
// Process the file private void IncomingUploadFile (PacketHeader, Connection connection, FileWrapper wrapper) sent from the client {try {writeFile (wrapper. _ fileData, @ "D: \" + wrapper. fileName); ResMsgContract contract = new ResMsgContract (); contract. message = "uploaded successfully"; // send the reply Message to the client connection. sendObject ("ResUploadFile", contract);} catch (Exception ex ){}}
// This method is from the private bool writeFile (byte [] pReadByte, string fileName) {FileStream pFileStream = null; try {pFileStream = new FileStream (fileName, FileMode. openOrCreate); pFileStream. write (pReadByte, 0, pReadByte. length);} catch {return false;} finally {if (pFileStream! = Null) pFileStream. Close ();} return true ;}
Step 2: Set the client
(1) connect to the server:
// Assign connInfo = new ConnectionInfo (txtIP. text, int. parse (txtPort. text); // if it fails, the exception message newTcpConnection = TCPConnection will pop up. getConnection (connInfo); TCPConnection. startListening (connInfo. localEndPoint); button1.Enabled = false; button1.Text = "connection successful ";
(2) Select a local file and upload it:
Private void button3_Click (object sender, EventArgs e) {openFileDialog2.Filter = "all files | *. * "; if (openFileDialog2.ShowDialog () = DialogResult. OK) {string parameter filename = System. IO. path. getFileName (openFileDialog2.FileName); FileWrapper fileWrapper = new FileWrapper (writable filename, ReadFile (writable); // send the image packaging class to the server and obtain the response ResMsgContract resMessage = newTcpConnection. sendReceiveObject <ResMsgContract> ("UploadFile", "ResUploadFile", 8000, fileWrapper); if (resMessage. message = "uploaded") {MessageBox. show ("the file has been uploaded to the server");} else {MessageBox. show ("file not sent successfully ");}}}
(3) FileWrapper class
During the communication between the client and the server, we noticed that the above program uses a FileWrapper class to transmit file objects.
FileWrapper class, which is stored in the MessageContract class library. This class is used to save the second-level data after file conversion.
Using System; using System. collections. generic; using System. text; using ProtoBuf; using System. drawing; using System. IO; using ProtoBuf; namespace MessageContract {[ProtoContract] public class FileWrapper {// <summary> // stores the Image object as a private byte array /// </summary> [ProtoMember (1)] public byte [] _ fileData; // <summary> // image name // </summary> [ProtoMember (2)] public string FileName {get; set ;} /// <summary> /// private non-parameter constructor used for deserialization // </summary> private FileWrapper () {}/// <summary> /// create a new ImageWrapper class // </summary> /// <param name = "imageName"> </param>/ // <param name = "image"> </param> public FileWrapper (string fileName, byte [] file) {this. fileName = fileName; this. _ fileData = file ;}}}FileWrapper
After the work is completed, a small amount of Code helps us implement the function of transferring client files to the server.
Note: This method is not suitable for transferring large files. If the file is large, it is best to send the file in the form of multipart transfer.