"Unity3d plug-in tutorial and source Analysis" the best HTTP plugin besthttp "on"

Source: Internet
Author: User
Tags rfc

Brief introduction

Unity used to communicate with the server can use the native www, but the WWW does not provide many functions, can not meet many needs. So we can encapsulate the HTTP protocol ourselves to meet more needs. The use of the HTTP protocol in Unity Games is common because it is easy to operate, easy to implement, and often used in scenarios such as landing and uploading some resources such as downloads. If you want to achieve further control, you need to use the socket and define your own protocol.

The use of this plugin also has a focus on cross-platform, because in C # own HttpWebRequest can also be achieved.

The following is a brief introduction to HTTP and sockets:

http Connection: The HTTP connection is called a short connection, that is, the client sends a request to the server, the server side of the response after the connection will be broken, slow, not very suitable for in-game real-time data transmission. The amount of data.

Because HTTP is actively releasing the connection after each request ends, the HTTP connection is a "short connection", which requires constant connection requests to the server to maintain the client program's online status. As a general practice, there is no need to obtain any data immediately, and the client will keep a "keep-connected" request to the server at regular intervals, and the server responds to the client after receiving the request, indicating that the client is "online". If the server can not receive the client's request for a long time, it is considered that the client "offline", if the client cannot receive a reply from the server for a long time, it is considered that the network has been disconnected.

Socket Connection : Socket is the so-called long connection, in theory, the client and server side once established connection will not be active disconnection, but due to various environmental factors may be disconnected, such as: Server or client host down, network failure, Or there is no data transfer between the two for a long time, the network firewall may disconnect the connection to free up network resources. So when there is no data transmission in a socket connection, it is necessary to send a heartbeat message in order to maintain the connection ~ ~ The specific heartbeat message format is defined by the developer itself.

For the difference between a socket connection and an HTTP connection, please refer to

Http://www.cnblogs.com/devinzhang/archive/2012/01/13/2321826.html

http://www.xuanyusong.com/archives/1948

Besthttp is an RFC 2616-based http/1.1 implementation that supports almost all unity-supported mobile and host platforms, see official documentation.

The following are mainly from official documents, and there will be some additional information.

Besthttp's goal is to become an easy-to-use and powerful unity plugin that takes full advantage of the http/1.1 potential.

Installation:

The plugins directory under the Besthttp directory needs to be moved to the assets directory, in fact the script BestHTTPInstaller.cs will automatically complete the process after the import is complete, using the [Initializeonload] feature, We'll talk about it later.

One thing to note is that unity is below version 3.5 and needs to be removed from the WP8 directory in the plugins directory.

Let's start with some basic introductions:

First, the using Besthttp is added; The statement

Get Requests

The simplest way to make a request to the server is to create a HttpRequest object that provides a URL and a callback function to the constructor. After creating a new HttpRequest object, we only need to call the Send () function to send the request.

Let's look at an example:

 1  httprequest request = new  HttpRequest (new  Uri ("Https:// google.com "), onrequestfinished);  2  request. Send ();  3   Onrequestfinished (HttpRequest request, HttpResponse response)  4  { 5  Debug.Log ("Request finished! Text Received: "+ response. Dataastext);  6 } 


The callback function receives two parameters, one is the original HttpRequest object and the other is the HttpResponse object that hosts the server response. If an error occurs, the HttpResponse object is empty and has a exception property to display the possible errors. The request is handled separately in different threads, and the call callback function is in the main thread of unity, so we don't have to do any thread synchronization.

In this case, we don't need any temporary variables,

New HttpRequest (new Uri ("https://google.com"), (request, Response) =>debug.log ("finished!")). Send ();

POST Requests

The above example is a simple get request, and if we do not specify a method, all requests will default to the GET request. The constructor contains a parameter that can specify the request method:

1 New HttpRequest (new Uri ("yourserver.com/Posturi"),2httpmethods.post,3 onrequestfinished); 4 request. AddField ("FieldName", "Field Value"); 5 request. Send ();

If you want to post any data without setting a domain, you can use the RawData property.

1 New HttpRequest (new Uri ("yourserver.com/Posturi"),httpmethods.post,onrequestfinished ); 4 request. RawData = Encoding.UTF8.GetBytes ("Field Value"); 5 request. Send ();

In addition to the get and post methods, other methods can be used in the same way.

How to get the downloaded data

Usually we get some data from the server through the request, the raw byte data can be obtained through the data property of the HttpResponse object, and we'll take a look at an example to download the image:

1 New HttpRequest ( "http://yourserver.com/path/to/image.png"), (request, response) = =  2{3varnew texture2d (00); 4 Tex. LoadImage (response. Data); 5 guitexture.texture = Tex; 6 }). Send ();      


There are, of course, more compact ways:

New HttpRequest ( "http://yourserver.com/path/to/image.png"), (request, response) = = guitexture.texture = Response. DATAASTEXTURE2D). Send ();


In addition to Dataastexture2d, there is a Dataastext property used to parse the response into a UTF8 string.

Note: All the examples in this article are not checked for errors, please add your own in the production environment.

You can also use Startcoroutine to yield HttpRequest,

1 New HttpRequest (Thenew Uri ("http://server.com")); 2 request. Send (); 3 yield return Startcoroutine (request); 4 Debug.Log ("Request finished! Downloaded Data: "+ request. Response.dataastext);

Debug.Log will only be called after the request is completed.

Advanced Topics:

Some of the higher-order usages of besthttp are discussed below

We can easily turn some features on or off through the HttpRequest constructor. Here are the parameters:

Methodtype: Determines what requests are made to the server. The default Methodtype
It's httpmethods.get.
Iskeepalive: Tell the server we want the TCP connection to remain on so that successive htttp requests do not have to open the connection again. If we keep it open by default, it will save a lot of time. If we are sure that the request will not be so frequent, it can be set to false. The default value is true.

Some information about the keepalive:

Http://www.cnblogs.com/huangfox/archive/2012/03/31/2426341.html

Http://www.cnblogs.com/skynet/archive/2010/12/11/1903347.html

So don't expect this to replace the long connection of the socket.
DisableCache: Tells the besthttp system to use or not the entire caching mechanism. If this value is true, then the system does not go to the cache to find the stored response,
And the response is not cached. The default value is False.
Verification system

Besthttp supports basic and digest authentication through HttpRequest's authentication properties:

1 usingbesthttp.authentication;2 varRequest =NewHttpRequest (NewUri ("https://httpbin.org/digest-auth/auth-int/usr/paswd"), (req, resp)3=4 {5     if(resp. StatusCode! =401)6Debug.Log ("Authenticated");7 Else8Debug.Log ("Not authenticated");9     Debug.Log (resp. Dataastext);Ten }); OneRequest. Credentials =NewCredentials ("usr","paswd"); ARequest. Send ();


For verification, you can refer to:

http://blog.csdn.net/dyllove98/article/details/9255719

Streaming media

The callback function that we provide for the HttpRequest constructor is called only once after the server responds to the full download complete processing. If this is the case, downloading large files on a mobile device will quickly run out of memory and the application will crash. To avoid this, besthttp is designed to handle such problems easily: only by setting a flag to true, our callback function is called after each predetermined amount of data is downloaded. In addition, if we do not close the cache, the response of the download is cached so that we can get the entire response from the local cache, and we do not have to touch the server with our code. (PS: The server must send the correct header: headers ("Expires"
Header:)

1 varRequest =NewHttpRequest (NewUri ("Http://yourserver.com/bigfile"), (req, resp) =2 {3list<byte[]> fragments =resp. Getstreamedfragments ();4     //Write out the downloaded data to a file:5 using(FileStream fs =NewFileStream ("Pathtosave", filemode.append))6     foreach(byte[] Datainchfragments)7Fs. Write (data,0, data. Length);8     if(resp. isstreamingfinished)9Debug.Log ("Download finished!");Ten }); OneRequest. Usestreaming =true; ARequest. Streamfragmentsize =1*1024x768*1024x768;//1 megabyte -Request. DisableCache =true;//already saving to a file, so turn off caching -Request. Send ();

Here is a brief description of what we did above
1. We switched the flag bit-usestreaming to true, so our callback function can be called repeatedly.

2.StreamFragmentSize indicates the maximum amount of data we want to cache before invoking the callback function.

3. Our callback function is called whenever the streamfragmentsize-sized chunk is downloaded and is called again after isstreamingfinished is set to true.

4. To get the downloaded data, we need to call the Getstreamedfragments () function, we should save its result in a temporary variable, because the internal cache will be emptied at the end of this call, so subsequent calls will return NULL.

5. We have closed the cache in this example because we have saved the downloaded file and we do not want to occupy too much space.

Cache

The cache is also based on the http/1.1 RFC. It uses header information to store and validate responses. The caching mechanism works in the background and we just need to decide whether to enable it. If the cached response has a ' Expires ' header with a future time, Besthttp will use the cached response and will not authenticate to the server. This means that we do not need to initialize any TCP connections. This allows us to save time, bandwidth, and can be used offline.

Although the cache is automatic, we can still control some, or we may get some information by using some common functions of the Httpcacheservice class:

Beginclear (): It clears all caches on another thread.
Beginmaintainence (): With this function, we can delete the cached entries based on the most recent access time. It deletes the cache entry with the last access time earlier than the specified time. We can also use this function to keep the cache size:
Delete the cache that has not been accessed in the last two weeks, and then delete the entry to keep the cache size below 50M, starting with the earliest.
Httpcacheservice.beginmaintainence (New Httpcachemaintananceparams (Timespan.fromdays (14),
50 * 1024 * 1024));
Getcachesize (): Returns the cache size, byte representation

Getcacheentrycount (): Returns the number of entries stored in the cache. The average cache entry size can be computed like this by float avgsize = getcachesize ()/(float) getcacheentrycount ().

"Unity3d plug-in tutorial and source Analysis" the best HTTP plugin besthttp "on"

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.