Implement TCP breakpoint upload, background C # service implementation receive

Source: Internet
Author: User

Implement TCP breakpoint upload, background C # service implementation receive

Terminal implementation of large file upload has always been a relatively difficult technology, which involves the backend and front-end interaction, stability and traffic size, and the implementation of the principle of everyone has their own ideas, the back-end mainstream with more than the HTTP to achieve, because most of the implementation of the breakpoint download. However, stability can not be guaranteed, once disconnected, unable to continue transmission. So you have to take another popular approach, TCP uploads large files.

Online to find some information, most of the breakpoint download, and then is a separate C # side of the upload received, or HTTP, or only Android, due to the task is tight, the preferred solution is HTTP first to implement the file upload, the terminal using the Post method, the file directly to the backend, The backend is obtained through file.

Android side:

Requestparams params = new Requestparams (); File File = GetTempFile ();//Get local file        try {            params.put ("file", file);        } catch (FileNotFoundException E1) {            e1.printstacktrace ();        }        Asynchttputil.post (URL + "/upload", params, new Jsonhttpresponsehandler () {...

Back end:

var file = request.files["file"];  File. SaveAs (Upfilename);

There are other better ways to handle this, or you can Liu it in, not through the file format. In the case of good network, but the network almost often upload half of the drop line or a number of client uploads are not connected to the situation, for large files extremely unstable, so hurriedly develop TCP protocol file breakpoint upload.

Also has the Netizen realizes the HTTP breakpoint to upload, since the big file does not, that will divide the file into the small file to upload, the pure net Main method:

Upload:

 bool result = true;            Long cruuent = 0;            FileStream fstream = new FileStream (FileName, FileMode.Open, FileAccess.Read);                         BinaryReader breader = new BinaryReader (fstream);            Analog breakpoint Upload, the first time only upload 100 bytes long length = 100;            FileName = filename.substring (filename.lastindexof (' \ \ ') + 1);                 #region start uploading the file try {byte[] data;                    #region split file upload for (; cruuent <= length; cruuent = cruuent + byteCount) { if (cruuent + byteCount > Length) {data = new Byte[convert.toint64 (Leng                        Th-cruuent)];                    Breader.read (data, 0, Convert.ToInt32 ((length-cruuent)));                        } else {data = new Byte[bytecount];                Breader.read (data, 0, ByteCount);    } try {Hashtable parms = new Hashtable (); Parms.                        ADD ("filename", filename); Parms. ADD ("NPOs", cruuent.                        ToString ());                    byte[] Byremoteinfo = postdata (Serverpath + "uploadserver.aspx", data, parms); } catch (Exception ex) {msg = ex.                        ToString ();                        result = false;                    Break } #endregion}} catch (Exception ex) {msg = ex.                ToString ();            result = false;                } finally {breader.close ();            Fstream.close (); } GC. Collect ();

First divide the file into small streams, npos the location of the breakpoint, that is, the size that has been uploaded, and then loop through all the packages.

Background receive:

 <summary>////Save file (get filename from URL parameter, current pointer, save file stream to current pointer)////If this is the first upload, the current pointer is 0, code execution is the same as continuation, except that the pointer is not offset//</s        ummary> public void Saveuploadfile () {string filename = request.params["filename"];        Long NPOs = Convert.toint64 (request.params["NPOs"]);               int uploadlength = Convert.ToInt32 (Request.InputStream.Length);        String path = Server.MapPath ("/uploadserver");        filename = path + "//upload//" + filename;        FileStream fstream = new FileStream (FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);        Offset pointer Fstream.seek (NPOs, Seekorigin.begin);        Gets the file stream from the client's request BinaryReader Breader = new BinaryReader (request.inputstream);            try {byte[] data = new Byte[uploadlength];            Breader.read (data, 0, uploadlength);        Fstream.write (data, 0, uploadlength); } catch {//todo add exception handling} finally {//free stream FSTream.            Close ();        Breader.close (); }    }

Focus on Fstream.seek (NPOs, Seekorigin.begin); Receives the save from the breakpoint location.

Interested can be realized by themselves.

Now the main talk about the client TCP upload, background TCP receive, the main idea is: The Android read local files file name, file size upload to the server (file name must be globally unique), the server will be based on the file name query whether uploaded, if uploaded, The size of the transmitted file, which is the breakpoint position, is passed to the terminal, the terminal receives the breakpoint location, and then reads the file from the breakpoint location intermittently, until it is complete. If not uploaded, the server creates a cache file to receive.

Look at the code android:

String head = "length=" + uploadfile.length () + "; filename=" + filename socket socket = new Socket ("192.168.0.123", 7080);                    OutputStream OutStream = Socket.getoutputstream (); Outstream.write (Head.getbytes ());//Send Pushbackinputstream instream = new Pushbackinputstream (socket.get                    InputStream ()); String response = Streamtool.readline (instream);//Read string[] items = Response.split (";"); Final string position = Items[0].substring (items[0].indexof ("=") + 1);//Breakpoint position final string serviceur L = items[1].substring (items[1].indexof ("=") + 1);//Save to Server path Randomaccessfile Fileoutstream = new Randomaccessfile (                        UploadFile, "R");                        Fileoutstream.seek (integer.valueof (position));//Read the file from the breakpoint location byte[] buffer = new byte[1024];                        int len =-1;              int length = integer.valueof (position);//uploaded size for local display          while (len = fileoutstream.read (buffer))! =-1) {outstream.write (buffer, 0, Len);                            length + = Len;                            Message msg = new Message ();                            Msg.getdata (). Putint ("size", length);                        Update the Upload Progress Handler.sendmessage (msg); }
if (length = = Uploadfile.length ()) {
If equal, the upload is successful
}

Back-end Processing:

private static TcpListener listener;//server monitoring   IPAddress iphost = ipaddress.any;  Listener = new TcpListener (iphost, 7080);                    Listener. Start ();//Turn on the monitor Socket remotesocketclient = listener. AcceptSocket ();                    device = new device (remotesocketclient);//Open a thread to process                    Threaddev = new Thread (new ThreadStart (device). Scan));                    Device.curentthread = Threaddev;                    Threaddev. IsBackground = true;                    Threaddev. Start ();
Scan Processing Method:
 string[] items = Strgetcontent.split (';'); String filelength = Items[0]. Substring (Items[0].                    IndexOf ("=") + 1); string filename = items[1]. Substring (Items[1]. IndexOf ("=") + 1); File Save full path FilePath = Path.Combine (directorypath, filename);//Breakpoint position long                        Position = 0; if (file.exists (FilePath)) {using (FileStream reader = new FileStream (f Ilepath, FileMode.Open, FileAccess.Read, Fileshare.none)) {Posi tion = reader.                            Length;                                               }}//Return message response = "position=" + position + "; serviceurl=" + Dirpath + "/" + filename); After the server receives the client's request information, it returns the response information to the client:;p osition=0//serviceurl Waiter Saved file location/playfiles/video/2016/07/04/1141142221.mp4 buffersend = EncOding. UTF8.                        GetBytes (response); Remotesocketclient.send (Buffersend);

Then process the continuation of the content:

 Get the file content byte[] buffer = new Byte[buffersize];                        int received = 0; Long receive, length = long.                        Parse (filelength);                        FileInfo file = new FileInfo (FilePath); using (FileStream writer = file. Open (file. Exists?                            FileMode.Append:FileMode.CreateNew, FileAccess.Write, Fileshare.none)) { Receive = writer.                            Length; while (receive < length) {if (Received = Remotesocketclient . Receive (buffer)) = = 0) {program.messageadd ("IP" + REM OteSocketClient.RemoteEndPoint.ToString () + "" Receive pause!                                    ");                                Break } writer.                                Write (buffer, 0, received); Writer.                 Flush ();               Receive + = (long) received; }}if (Receive = = length) {Program.messageadd (" IP "" + remoteSocketClient.RemoteEndPoint.ToString () + "receive" + filename + "complete!" ");}

The main principle is to upload and receive from the breakpoint location.

Here is just the main code features, there are a lot of details, such as the terminal to show progress, so also to save progress, back-end files will not be misplaced, there are many file upload will be messy, multi-client upload is to create new threads or thread pool to handle and so on.

Implement TCP breakpoint upload, background C # service implementation receive

Related Article

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.