Unity program sends data to a Web server

I. INTRODUCTION

This article demonstrates a simple example, send data from the Unity program to the Web server, Web server receives the data and then return the data to the Unity program. HTTP does not come with their own mental and physical architecture design requires design.

Two, HTTP protocol

Unity of the WWW is based on network transmission function of the HTTP protocol, HTTP (hypertext transport protocol) protocol Hypertext protocol, which defines the rules of the World Wide Web data communication, it is the client, server model, the client and server must support HTTP. An important feature of HTTP is the protocol processing only one request per connection, when the client has finished processing the request, i.e., disconnected, to save transmission time.
HTTP protocol to transmit data using a variety of ways, Unity of WWW which mainly supports GET and POST method. GET method request will be appended to the URL, POST way is submission through the FORM form (form) a. GET method can only transmit up to 1024 bytes, POST way theoretically there is no limit. POST GET way higher than the security from a security point of view, so in actual use more options POST method.
Now, let's create a simple UI interface, provides two buttons, one for use GET and POST method to submit data to the server. (There will not build HTTP server can see my previous article Php and Apache environment configuration )

Third, the new Unity project, create a script

1. Create a new Unity project, create a script WebManager.cs, the game will assign it to any body in the scene.
2. Add a m_info properties and functions WebManager.cs OnGUI display UI:
string m_info = "Nothing";

    private void OnGUI()
    {
        GUI.BeginGroup(new Rect(Screen.width * 0.5f - 100,Screen.height * 0.5f -100,500,200),"");

        GUI.Label(new Rect(10,10,400,30),m_info);

        if (GUI.Button(new Rect (10,50,150,30),"GetData"))
        {
            
        }

        if (GUI.Button(new Rect(10,100,150,30),"Post Data"))
        {
            
        }

        GUI.EndGroup();
    }

Running the program, there will be two buttons in the window, and displays "Nothing", as shown in FIG. We will use the Get Data and Post Data buttons to send data to a Web server via GET and POST method, and the server returns the data passed to m_info properties appear on the screen.
Here Insert Picture Description

Four, GET requests

Next, we use the GET method to submit data to the server, including a user name and a password, the server receives returns a string.

Add a IGetData () script function in WebManager.cs, pay attention to the return type of the function is
IEnumerator IGetData()
    {
        WWW www = new WWW("http://47.101.204.7:8088/index.php?username=get&password=123456");
        yield return www;
        if (www.error != null)
        {
            m_info = www.error;
            yield return null;
        }

        m_info = www.text;
    }

This function, we first create a WWW instance to send GET requests to the specified IP address, follow after the IP address? Additional data for, here we send the two GET data is a username, password and the other is, their values ​​are get and 12345.

WWW instance will run in the background, yield return www waits reflected Web server.
If the error attribute WWW instance is not empty, Web server returns the data will be stored in the text attribute WWW instance.

Add code execution IGetData function OnGUI function:
if (GUI.Button(new Rect (10,50,150,30),"GetData"))
        {
            StartCoroutine(IGetData());
        }
Next, we want to create a PHP script in response to a GET request the WWW. New PHP project, created in index.php Web server root directory
<?php
if ( isset($_GET['username']) && isset($_GET['password']) )
      echo 'username is '.$_GET['username'].' and password is '.$_GET['password']; 
else
      echo "error!"; 
?>

This is a PHP code, isset function to determine whether the corresponding received GET request, if received, using the output of the echo function, and returns it to the Unity program. (In PHP, connecting the two strings are used, rather than +)

Tests are as follows

In Unity run the program, click Get Data button, and then receive the value returned by the server, the results are as follows:
Here Insert Picture Description

Five, POST request

Use POST and GET to submit data in a manner similar to, but we will put the string into a byte array.

Add a IPostData () script function in WebManager.cs:
IEnumerator IPostData()
    {
        Dictionary<string,string> headers = new Dictionary<string, string>();
        headers.Add("Content_Type","application/x-www-form-urlencoded");

        string data = "username=post&password=6789";
        byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data);
        WWW www = new WWW("http://47.101.204.7:8088/index.php",bs,headers);
        yield return www;

        if (www.error != null)
        {
            m_info = www.error;
            yield return null;
        }

        m_info = www.text;
    }

And GET is different is that the string stored in the data, not the front? Symbol, but still use the ampersand connection data, and finally we will string to a byte array. headers in previous versions is now changed to a HashTable Dictionary, which, by the value corresponding to the key, here we use it to save HTTP header.

Add code execution IPostData function OnGUI function:
if (GUI.Button(new Rect(10,100,150,30),"Post Data"))
        {
            StartCoroutine(IPostData());
        }

Modify the PHP script, add respond POST request:
<?php
if ( isset($_GET['username']) && isset($_GET['password']) )
      echo 'username is '.$_GET['username'].' and password is '.$_GET['password']; 
else if ( isset($_POST['username']) && isset($_POST['password']) )
      echo 'username is '.$_POST['username'].' and password is '.$_POST['password'];
else
      echo "error!"; 
?>

Tests are as follows:

Unity running the program, click Post Data button, and then receive the data returned by the server

Here Insert Picture Description

Published 62 original articles · won praise 5 · Views 3927

Guess you like

Origin blog.csdn.net/qq_42194657/article/details/103031573