Unity3d C # Socket download file (sync to)

Source: Internet
Author: User

Sequel Unity3d C # httpwebrequest An asynchronous download file that is still invalid because project compiles to il2cpp. Tip HttpWebRequest is not supported in the current version number. So we are looking for other ways.

Just the branch of the colleague also encountered the download file bug, but they are only part of the below, at least also better than my situation, so borrowed colleague's participation.


The structure is roughly to send an HTTP request to the server with a socket. Set up various HTTP headers, and then receive the data stream from the server.

First understand the HTTP header:

Typical request message: GET Http://download.microtool.de:80/somedata.exehost:download.microtool.deaccept:*/*pragma: No-cachecache-control:no-cachereferer:http://download.microtool.de/user-agent:mozilla/4.04[en] (Win95;I; NAV) range:bytes=554554-the first line in the previous example indicates that HttpClient (possibly a browser, downloader) obtains a file under the specified URL through the Get method.

The brown portion represents the information for the Request header field, and the green section represents the General header section. The host header domain specifies the intenet host and port number of the requested resource, which must represent the location of the original server or gateway that requested the URL. The http/1.1 request must include the master header domain, or the system will return with a 400 status code; Accept: Tell webserver what type of media you accept, */* means whatever type, type/* represents all subtypes under that type, Type/sub-type. Accept-charset: The browser affirms the character set it receives. Authorization: When the client receives a www-authenticate response from webserver, the header is used to respond to its authentication information to webserver. The contents of the User-agent header domain include the user information that made the request. The Referer header domain agrees that the client specifies the source resource address of the request URI, which allows the server to generate a fallback list that can be used to log in, optimize the cache, and so on.

He also agreed to the abolition or the wrong connection because the purpose of maintenance was traced. Assume that the requested URI does not have its own URI address. Referer cannot be sent. Assume that a partial URI address is specified. The address should be a relative address; The Range header field can request one or more child scopes of an entity.

For example, the first 500 bytes: bytes=0-499 represents the second 500 bytes: bytes=500-999 represents the last 500 bytes: bytes=-500 represents the range after 500 bytes: bytes=500-First and last byte: bytes= 0-0,-1 specify several ranges at the same time: bytes=500-600,601-999 but the server can ignore this request header, assuming that the unconditional get includes the range request header, the response is returned in the Status Code 206 (partialcontent) instead of 200 (OK) The response message (response header) responds to the first behavior of the message in the following format: Http-version Status-code reason-phrasehttp-version represents the supported HTTP version number, for example, http/1.1. Status-code is a result code of three numbers. Reason-phrase provides Status-code with a simple textual description of the narrative.

Status-code is mainly used for automatic machine identification. Reason-phrase is mainly used to help users understand.

The first number of Status-code defines the category of the response, and the latter two numbers do not have a role to classify. The first number may take 5 different values: 1xx: Information Response class. Represents a request received and continues processing 2xx: Handles the success response class, which indicates that the action was successfully received, understood, and accepted by 3xx: Redirect Response class, in order to complete the specified action. You must accept further processing of the 4xx:client error, the client request includes a syntax error or is not running correctly 5xx: The server does not correctly run a correct request response header domain Consent server to pass additional information that cannot be placed on the status line. These domains mainly describe the information of the server and Request-uri further information. The response header fields include age, location, proxy-authenticate, public, Retry-after, Server, Vary, Warning, and Www-authenticate. The expansion of the response header domain requires both communication support. Suppose there is an unsupported response header field, which is typically handled as the Entity header field. Typical response message: http/1.0 okdate:mon,31dec200104:25:57gmtserver:apache/1.3.14 (Unix) content-type:text/ Htmllast-modified:tue,17apr200106:46:28gmtetag: "a030f020ac7c01:1e9f" Content-length:39725426content-range: bytes554554-40279979/40279980 the first line in the previous example represents an HTTP service-side response to a GET method. The brown part represents the Response header field information, the green part represents the General header section, and the red part represents the Entity header field information.

The location response header is used to redirect the recipient to a new URI address. The server response header includes software information for the original server that processed the request. This domain can include multiple product identities and gaze, and product identification is generally sorted by importance. Entity messages (Entity headers and entities) request and response messages can include entity information, which is typically composed of entity header fields and entities.

The Entity header field includes the original information about the entity, including allow, Content-base, content-encoding, Content-language, Content-length, Content-location, CONTENT-MD5, Content-range, Content-type, Etag, Expires, Last-modified, Extension-header. Extension-header agrees that the client defines a new entity header, but these domains may not be recognized by the recipient. The Content-type entity header is used to indicate to the receiver the media type of the entity. Specifies the entity media type that the head method sends to the receiver. Or the request media type sent by the Get method, indicating what MIME type the following document belongs to. The content-length represents the number of bytes actually transferred. Allow entity headers to which request methods (such as Get, post, and so on) are supported by the server. Content-range represents the range of the transfer, which specifies the insertion position of a part of the entire entity, and he also indicates the length of the entire entity. When the server returns a partial response to the customer, it must describe the scope of the narrative response coverage and the entire length of the entity.

General format: Content-range:bytes-unitspfirst-byte-pos-last-byte-pos/entity-legth For example, transfer the first 500 bytes in the form of a field: Content-range: BYTES0-499/1234 assumes that an HTTP message includes this section (for example,. A response to a range request or overlapping requests for a range of scopes). Content-encoding refers to the encoding (Encode) method of the document.

The

Entity can be a coded stream of bytes encoded by content-encoding or Content-type, whose length is defined by content-length or Content-range. Appendix: HTTP Header Specific explanation 1, accept: Tell webserver oneself accept what medium type, */* means no matter what type. type/* represents all sub-types under this type. Type/sub-type. 2, Accept-charset: The browser affirms itself to receive the character set accept-encoding: The browser declares itself to receive the encoding method, usually specifies the compression method, whether compression is supported, what compression method (gzip) is supported. Deflate) Accept-language:: The browser affirms that the language you receive differs from the character set: Chinese is language, Chinese has multiple character sets. For example Big5. GB2312,GBK and so on. 3. Accept-ranges:webserver Indicates whether it accepts a request to obtain part of an entity (such as a part of a file).

Bytes: Accept, none: Indicates not accepted. 4. Age: When the proxy server responds to a request with its own cached entity, it uses that header to indicate how long it has been from the time it was generated to now. 5. Authorization: When the client receives a www-authenticate response from webserver, it uses the header to respond to its own authentication information to webserver. 6, Cache-control: Request: No-cache (do not cache the entity, the requirement is now from webserver to fetch) Max-age: (Only accept the age value is less than the Max-age value.) And there are no expired objects) Max-stale: (Can accept past objects, but the expiration time must be less than Max-stale value) Min-fresh: (Accept the Cache object whose novelty life is greater than the sum of its current age and Min-fresh values): Public ( Able to respond with Cached content to any user) private (can only use cached content to respond to the previously requested content of the user) No-cache (able to cache, but only with webserver verified that it is valid, Ability to return to client) Max-age: (The expiration time of the object included in this response) All:no-store (does not consent to cache) 7, Connection: Request: Close (Tell webserver or proxy server, after the response of this request is completed, Disconnect, do not wait for the connection to be requested). KeepAlive (Tell webserver or proxy server, after completing the response of this request, remain connected, waiting for the connection request). Response: Close (the connection is closed). KeepAlive (connection is maintained, waiting for a request for this connection).

Keep-alive: Assuming the browser request remains connected, the header indicates how long (in seconds) you want the WEB server to remain connected. For example: keep-alive:3008, Content-encoding:webserver shows what compression method (gzip) you are using. Deflate) compresses the object in the response.

For example: CONTENT-ENCODING:GZIP9, Content-language:web server tells the browser the language of the object it responds to. 10. Content-length:web server tells the browser the length of the object it responds to. For example: content-length:2601211, Content-range:web server indicates which part of the object the response includes. For example: Content-range:bytes 21010-47021/4702212, Content-type:web server tells the browser what type of object it responds to. For example: Content-type:application/xml13, ETag: Is an object (for example, URL) of the flag value, in terms of an object, such as an HTML file. Assumptions have been altered. The etag will not change, so the role of the etag is almost identical to that of last-modified. Primarily for WEB server to infer whether an object has changed. For example, when an HTML file was previously requested, the ETag was obtained, and when the file was requested this time, the browser sent the previously obtained ETag value to the Web server. The WEB server then compares the ETag to the current etag of the file, and then knows that the file has not changed.

14. Expired:webserver indicates when the entity will expire, for expired objects. Only after having verified its validity with webserver. Ability to respond to customer requests. It's http/1.0 's head.

For example: Expires:sat, 10:02:12 GMT15, host:client Specify the domain/IP address and port number of the webserver you want to access. For example: Host:rss.sina.com.cn16, If-match: Assuming that the object's ETag has not changed, it actually means that the object has not changed before it runs the requested action. 17. If-none-match: Assuming that the ETag of the object changes, it actually means that the object has changed before the requested action is run.

18. If-modified-since: Suppose the requested object has changed after the specified time in the header. To run the requested action (for example, to return an object), or return code 304, telling the browser that the object has not changed. For example: If-modified-since:thu, 09:14:42 GMT19, If-unmodified-since: If the requested object is not changed after the time specified in the header, the requested action (for example, return object) is run. 20. If-range: Browser tells WEB server. Suppose the object I requested has not changed. Give me the missing part, assuming the object has changed, give me the whole object. The browser lets the WEB server infer whether the object has changed by sending the ETag of the requesting object or the last time that it has been modified. Always used with the Range header. 21, Last-modified:web server think of the object's last change time, such as the last time the file changes, dynamic page of the last generation time and so on. For example: Last-modified:tue, May 02:42:43 GMT22, Location:web server tells the browser that the object you are trying to access has been moved to another location. To the location specified in the header.

For example: Location:http://i0.sinaimg.cn/dy/deco/2008/0528/sinahome_0803_ws_005_text_0.gif23, Pramga: mainly use PRAMGA: No-cache. Equivalent to Cache-control:no-cache.

For example: Pragma:no-cache24, Proxy-authenticate: The proxy server responds to the browser and requires it to provide proxy authentication information. Proxy-authorization: The browser responds to the proxy server's authentication request and provides its own identity information. 25. Range: The browser (for example, Flashget multithreaded download) tells the WEB server what part of the object it wants to take.

For example: Range:bytes=1173546-26, Referer: The browser indicates to the Web server which page/url obtained/clicked on the URL/url in the current request. For example: Referer:http://www.sina.com/27, Server:web Server to indicate what the software and version number and other information. For example: server:apache/2.0.61 (Unix) 28, User-agent: The browser indicates its identity (which browser). For example: user-agent:mozilla/5.0 (Windows; U Windows NT 5.1; ZH-CN; rv:1.8.1.14) gecko/20080404 firefox/2, 0, 0, 1429, Transfer-encoding:web server shows how to encode this response message body (not the object inside the message body). For example, whether to split blocks (chunked). For example: Transfer-encoding:chunked30, Vary:webserver Use the contents of the header to tell the Cache server. Under what conditions the ability to respond to a request with the object returned by this response.

If the source webserver is receiving the first request message. The head of its response message is: Content-encoding:gzip; Vary:content-encoding then the Cache server parses the header of the request message and checks to see if its accept-encoding is consistent with the Vary header value of the previous response, that is, whether to use the same content encoding method, which prevents Cache server responds to a browser that does not have the ability to decompress by using the compressed entity in its own cache. For example: Vary:accept-encoding31, Via: Lists which proxy servers The response from client to OCS or in the opposite direction passes through. What protocol (and version number) they are using to send the request. When a client request arrives at the first proxy server. The server will add the Via header to the request itself. and fill in your own information when the next proxy server receives a request from the first proxy server. The VIA header of the request from the previous proxy server is copied in the request itself, and the relevant information is added to the back, and so on, when OCS receives the last Proxy server request, check the VIA header to know the route that the request passes through.

For example: via:1.0 236.d0707195.sina.com.cn:80 (SQUID/2.6.STABLE13) ===================================================== ==========================http Request message Header instance: HOST:RSS.SINA.COM.CNUSER-AGENT:MOZILLA/5, 0 (Windows; U Windows NT 5, 1; ZH-CN; Rv:1, 8, 1, +) gecko/20080404 firefox/2, 0, 0, 14accept:text/xml,application/xml,application/xhtml+xml,text/html;q=0, 9,text/plain;q=0, 8,image/png,*/*;q=0, 5accept-language:zh-cn,zh;q=0, 5accept-encoding:gzip, Deflateaccept-charset:gb2312,utf-8;q=0, 7,*;q=0, 7keep-alive:300connection:keep-alivecookie:userid= C5BYPXRIMDMSIQMSBPNE1VN8ZQMDWSM3WRLEB3VRWTNRTW <--Cookieif-modified-since:sun, June 2008 12:05:30 Gmtcache-control:max-age=0http Response message Header instance: status:ok-200 <--Response Status code that represents the results of Web server processing. Date:sun, June 12:35:47 gmtserver:apache/2, 0, (Unix) Last-modified:sun, June 12:35:30 Gmtaccept-ranges:byt Escontent-length:18616cache-control:max-age=120expires:sun, June 12:37:47 gmtcontent-type:application/ Xmlage:2x-cache:hit from 236-41, D07071951, Sina, COM, CN <--Reverse proxy Server uses the HTTP header via:1.0 236-41.d07071951.sina.com.cn:80 (squid/2.6.stable13) connection:close


Then here is an instance. or download the previous file:

Using unityengine;using system.collections;using system.net;using system.io;using system;using System.Threading; Using system.text;using system.net.sockets;using system.text.regularexpressions;public class NewBehaviourScript:    monobehaviour {www www = null;    UINT ContentLength = 0;    int n = 0;    NetworkStream NetworkStream;    FileStream FileStream;    Socket Clientsocket;    int read = 0;//Use the This for Initializationvoid Start () {Downloadbysocket ();}        void Downloadbysocket () {String host = "dev.thisisgame.com.cn";            String querystr = "Get/disunity_v0.3.4.zip http/1.1\r\n" + "host:dev.thisisgame.com.cn\r\n" +            "user-agent:undefined\r\n" +//"range:bytes=0-10\r\n" + "connection:keep-alive\r\n" +        "\ r \ n";        Debug.Log ("querystr=" + querystr);        Clientsocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, Protocoltype.ip); Clientsocket.connect (host, 80);       NetworkStream = new NetworkStream (clientsocket);        var bytes = Encoding.Default.GetBytes (QUERYSTR); Networkstream.write (bytes, 0, bytes.        Length);        var breader = new BinaryReader (NetworkStream, Encoding.default);        String response = "";        String line;        char c;                Try {does {line = "";                c = ' \u0000 ';                    while (true) {c = Breader.readchar ();                    if (c = = ' \ r ') break;                Line + = C;                } c = Breader.readchar ();            Response + = line + "\ r \ n"; } while (line.        Length > 0);        } catch (System.Exception ex) {debug.logerror (ex);        } Debug.Log (response);        Regex recontentlength = new Regex (@ "(? <=content-length:\s) \d+", regexoptions.ignorecase); ContentLength = uint. Parse (RecontentleNgth. Match (response).        Value); Debug.Log ("contentlength=" + contentlength); #if unity_editor fileStream = new FileStream ("Disunity_v0.3.4.zip", Fil emode.create); #else fileStream = new FileStream (application.persistentdatapath+ "Disunity_v0.3.4.zip", Filemode.crea    TE); #endif m_bdownloadstart = true;    } bool M_bdownloadstart = FALSE;        void Update () {//return; if (M_bdownloadstart) {if (n < contentlength) {byte[] buffer = new byte[2                56 * 1024]; if (networkstream.dataavailable) {read = Networkstream.read (buffer, 0, buffer.                    Length);                    n + = read;                FileStream.Write (buffer, 0, read);            } Debug.Log ("Downloaded:" + n + "of" + contentlength + "bytes ...");                } else {debug.logerror ("Download Finish");        Filestream.flush ();        Filestream.close ();                Clientsocket.close ();            M_bdownloadstart = false; }        }    }}




Copyright NOTICE: This article transfers from Http://blog.csdn.net/huutu reprint please carry http://www.thisisgame.com.cn

Unity3d C # Socket download file (sync to)

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.