Unity3d C # Socket download file (synchronous to)

Source: Internet
Author: User
Tags ranges

Unity3d C # HttpWebRequest Asynchronous download file, because it is still invalid to compile the project into Il2cpp, prompting HttpWebRequest is not supported in the current version, so seek other ways.

Just the branch of the colleague also encountered the download file bug, but they are only able to download part, at least better than my situation, so borrowed colleagues reference.


The structure is basically to use the socket to send HTTP requests to the server, and then set various HTTP headers, and then receive the data stream sent by 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 the HTTP client (possibly a browser, downloader) obtains the 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 requesting resource, and must represent the location of the originating server or gateway that requested the URL. The http/1.1 request must contain the host header domain or the system will return with a 400 status code; Accept: Tell the Web server what type of media it accepts, */* represents any 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 the Web server, it uses that header to respond to its own authentication information to the Web server. The contents of the User-agent header domain contain the user information that made the request. The Referer header domain allows the client to specify 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 allows the abolition or wrong connection to be traced for maintenance purposes. If the requested URI does not have its own URI address, Referer cannot be sent. If you specify a partial URI address, the address should be a relative address; The Range header field can request one or more child scopes of the 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, and if the unconditional get contains a range request header, the response will return with 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, for example, http/1.1. Status-code is a result code of three numbers. Reason-phrase provides a simple text description for Status-code. Status-code is mainly used for machine automatic 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: The information response class, which represents receiving the request and continues processing 2xx: Processing the Success response class, indicating that the action was successfully received, understood, and accepted 3xx: Redirect Response class, in order to complete the specified action, must accept further processing 4xx: Client error, The client request contains a syntax error or is not properly executed 5xx: The server does not correctly execute a correct request response header domain allows the server to pass additional information that cannot be placed on the status line, which primarily describes the server's information and Request-uri further information. The Response header field contains age, location, proxy-authenticate, public, Retry-after, Server, Vary, Warning, and Www-authenticate. The expansion of the response header field is required for both sides of the communication, and if there is an unsupported response header field, it will generally be 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 contains software information for the originating server that processed the request. This field can contain multiple product identities and annotations, and product identities are generally sorted by importance the entity messages (Entity headers and entities) Request messages and response messages can contain entity information, which generally consists of entity header fields and entities. Solid HeadThe field contains the original information about the entity, and the entity header includes 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 allows clients to define new entity headers, but these domains may not be recognized by the recipient. The Content-type entity header is used to indicate the media type of the entity to the receiver, specify 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 subsequent 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 extent of the 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 If an HTTP message contains 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. An 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 1, accept: Tell the Web server to accept what media type, */* represents any type, type/* represents all sub-types under the 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 is supported (gzip, Deflate) Accept-language:: The browser affirms the difference between the language and the character set: Chinese is language, Chinese has a variety of character sets, such as big5,GB2312,GBK and so on. 3. The Accept-ranges:web server indicates whether it accepts requests 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 is used to indicate how long the entity has been from the time it was produced to the present. 5. Authorization: When the client receives the Www-authenticate response from the Web server, it uses the header to respond to its own authentication information to the Web server. 6, Cache-control: Request: No-cache (do not cache the entity, request now from the Web server to fetch) Max-age: (Only accept the age value is less than the Max-age value, and there is no expired object) Max-stale: (Can accept past objects, However, the expiration time must be less than Max-stale value) Min-fresh: (accepts cached objects whose freshness life is greater than the sum of its current age and Min-fresh values) Response: public (can respond to any user with Cached content) Private (only cached content responds to the user who previously requested the content) No-cache (can be cached, but only after the Web server has verified that it is valid to be returned to the client) Max-age: (The expiration time of the object contained in this response) all: No-store (cache not allowed) 7, Connection: Request: Close (Tell the Web server or proxy server, after completing the response of this request, disconnect, do not wait for subsequent requests for this connection). KeepAlive (tells the Web server or proxy server, after completing the response of this request, remains connected, waiting for subsequent requests for this connection). Response: Close (the connection is closed). KeepAlive (connection is maintained, waiting for subsequent requests for this connection). Keep-alive: If the browser requests to remain connected, the header indicates how long (in seconds) you want the WEB server to remain connected. For example: The keep-alive:3008, Content-encoding:web server indicates what compression method (Gzip,deflate) is used to compress the objects in the response. For example: CONTENT-ENCODING:GZIP9, the Content-language:web server tells the browser the language of the object it responds to. 10. The Content-length:web server tells the browser the length of the object it responds to. For example: content-length:2601211, ConteThe Nt-range:web server indicates that the response contains part of the object that is the entire object. For example: Content-range:bytes 21010-47021/4702212, the Content-type:web server tells the browser what type of object it responds to. For example: Content-type:application/xml13, ETag: is an object (such as a URL) of the flag value, in terms of an object, such as an HTML file, if modified, its etag will not be modified, so the role of the etag with The Last-modified function is similar, mainly for the WEB server to determine whether an object has changed. For example, when a previous request for an HTML file, the ETag was obtained, and when the file is requested, the browser will send the previously obtained ETag value to the Web server, and then the Web server will compare the ETag with the file's current etag, and then know that the file has not changed The 14. The Expired:web server indicates when the entity will expire and, for expired objects, can be used to respond to customer requests only after it has verified its validity with the Web server. It's http/1.0 's head. For example: Expires:sat, 10:02:12 GMT15, Host: The client specifies the domain/IP address and port number of the Web server that you want to access. For example: Host:rss.sina.com.cn16, If-match: If the object's ETag does not change, it actually means that the object has not changed before the requested action is executed. 17. If-none-match: If the ETag of an object changes, it also means that the object has changed to perform the requested action. 18. If-modified-since: If the requested object is modified after the time specified by the header, the requested action (such as the return object) is executed, otherwise the code 304 is returned, telling the browser that the object has not been modified. For example: If-modified-since:thu, APR 09:14:42 GMT19, If-unmodified-since: If the requested object has not been modified since the time specified in the header, the requested action (such as returning an object) is performed. 20. If-range: The browser tells the WEB server that if the object I requested does not change, give me the missing part, and if the object changes, give me the whole object. The browser sends the request object's ETag or the last modified time it knows to the WEBServer to determine if the object has changed. Always used with the Range header. 21, the Last-modified:web server considers the last modification time of the object, such as the last modification time of the file, the last generation time of the dynamic page, etc. 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 to fetch. 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 (such as Flashget multi-threaded download) tells the WEB server what part of the object you want 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 indicates what software and version of the 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 indicate how to encode this response message body (not the object inside the message body). For example, whether to divide the block (chunked). For example: The TRANSFER-ENCODING:CHUNKED30, Vary:web server uses the contents of the header to tell the Cache server under what conditions the object returned by this response responds to subsequent requests. IfWhen the source Web server receives the first request message, the header of its response message is: Content-encoding:gzip; Vary:content-encoding then the cache server parses the header of the subsequent request message and checks if its accept-encoding is consistent with the Vary header value of the previous response, that is, whether the same content encoding method is used, which prevents the cache The server responds to the compressed entity in its own Cache to a browser that does not have the ability to decompress. For example: Vary:accept-encoding31, Via: Lists which proxy servers The response from the client to OCS or in the opposite direction passed, and what protocol (and version) they used to send the request. When the client request arrives at the first proxy server, the server adds via header in its own request and fills in its own information, and when the next proxy receives a request from the first proxy server, it copies the Via header of the request from the previous proxy server in its own request. and add their own information to the back, and so on, when OCS receives the last Proxy server request, check Via header, know the route that the request passes. 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, indicating the results of the 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 HTTP headers used by the reverse proxy server from 236-41, D07071951, Sina, COM, cn <--, via:1.0 236-41.d07071951.sina.com.cn : (SQUID/2.6.STABLE13) Connection:close

Then here is an example, 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; }        }    }}




Unity3d C # Socket download file (synchronous to)

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.