[C # source sharing] Client program transmits "small file" to server through TCP communication

Source: Internet
Author: User

Source code (does not include the communication framework source code, the communication framework source code please download separately)

The previous article wrote how to send pictures through TCP communication to the client, a friend asked how to transfer files, this article will discuss how to send files.

For relatively small files, you can convert the file into byte form, with the contract class packaging, the server received, and then convert the bytes into a file, this is the way to implement this article, the advantages of this method is relatively simple and flexible, the disadvantage is not suitable for large file sending, also can not display the progress of file sending.

TCP-based communication mechanism, for larger files, this method is not feasible, large files using segmented send and re-synthesis of a better way, there is time to discuss how to send large files alone.

This program is based on the open source networkComms2.3.1 communication framework

Let's start with a look at the effect of the implementation

Server-side:

Client:

On the server side, we save the received image in the D packing directory (you can specify the path), open D to see the picture received as follows:

Let's take a look at the specific process

The first step is to set up the server side first

(1) Listening port:

 //  server starts listening for client requests  //  start listening on a T port  ipendpoint thepoint = new  IPEndPoint (Ipaddress.parse (txtip.text), int   false             ); Button1. Text  =   listen   " ; Button1.            Enabled  = false  ;  //  startlistening (); 

(2) for file upload write corresponding processing method:

   Networkcomms.appendglobalincomingpackethandler<filewrapper> ("uploadfile", Incominguploadfile);
   //processing files sent by the client        Private voidIncominguploadfile (packetheader header, Connection Connection, FileWrapper wrapper) {Try{WriteFile (Wrapper._filedata,@"D:\"+Wrapper.                                       FileName); Resmsgcontract Contract=Newresmsgcontract (); Contract. Message="Upload Successful"; //send reply message to clientConnection. SendObject ("Resuploadfile", contract); }            Catch(Exception ex) {}}
   //This method comes from Blog Park        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 two: Setting up the client

(1) Connect the server:

// Assigning a value            to a connection information object New int . Parse (Txtport.text));             // if not successful, the exception message            pops up Newtcpconnection = tcpconnection.getconnection (conninfo);            Tcpconnection.startlistening (conninfo.localendpoint);             false ;             " Connection Successful ";

(2) Select files from local and upload:

 Private voidButton3_Click (Objectsender, EventArgs e) {Openfiledialog2.filter="All Files |*.*"; if(Openfiledialog2.showdialog () = =DialogResult.OK) {stringShortFileName =System.IO.Path.GetFileName (openfiledialog2.filename); FileWrapper FileWrapper=NewFileWrapper (ShortFileName, ReadFile (openfiledialog2.filename)); //send a picture wrapper class to the server and get the return informationResmsgcontract resmessage = newtcpconnection.sendreceiveobject<resmsgcontract> ("UploadFile","Resuploadfile",8000, FileWrapper); if(Resmessage.message = ="Upload Successful") {MessageBox.Show ("file has been uploaded to the server"); }                Else{MessageBox.Show ("file not sent successfully"); }            }                     }

(iii) about the FileWrapper category

In the process of client-to-server communication, we notice that the above program uses a FileWrapper class to pass a file object.

The FileWrapper class, which is stored in the MessageContract class library, is used to save file-converted two-level data

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingProtobuf;usingSystem.Drawing;usingSystem.IO;usingProtobuf;namespacemessagecontract{[Protocontract] Public classFileWrapper {/// <summary>        ///storing an Image object as a private byte array/// </summary>[Protomember (1)]         Public byte[] _filedata; /// <summary>        ///Picture name/// </summary>[Protomember (2)]         Public stringFileName {Get;Set; } /// <summary>        ///private parameterless constructors need to be deserialized using the/// </summary>        PrivateFileWrapper () {}/// <summary>        ///Create a new Imagewrapper class/// </summary>        /// <param name= "ImageName" ></param>        /// <param name= "image" ></param>         PublicFileWrapper (stringFileName,byte[] file) {             This. FileName =FileName;  This. _filedata =file; }           }}
FileWrapper

Work to this finish, very little code volume, help us implement the delivery client file saved in the server function.

Note: This is not a good way to pass a larger file, and if the file is larger, it is best to send it as a staging file.

[C # source sharing] Client program transmits "small file" to server through TCP communication

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.