Preface:
In the previous several articles introduced the server side of the construction and client connection to the server side of the relevant implementation process, the next need to achieve data transmission between the client and the server side function
This use to make Unity login interface case to learn how to use Unity server and client for data transmission, the relevant code has been uploaded to Github, you can download the view: Unity-Socket
Client:
The UI structures,
First we need to add two input fields to the Canvas. You can right-click UI in the Hierarchy panel and select create two Input fields to create. After completion, the fields are named UserName and Password respectively to represent the incoming fields of account and Password data. In order to prompt the player for input, modify the Text in the Text component in the Placeholder child element after addition
Then add a Button as a data submission Button to trigger user login by monitoring Button click events
Effect:
Matters needing attention:
To ensure that the password format meets the standards, you can enter the password in the
Input Field
Select theContent Type
Select the appropriate input content type, to limit the user’s input format, account selectionName
, and the password is optionalPassword
:
The script
Script idea:
- First get the player input account password, you can use
InputField.text
Method to obtain the input content of the input box, and then determine whether the obtained account password meets the conditions, if the conditions are met, the account password two contents will be combined - The next step is to connect to the corresponding server, and then convert the combined account password into a byte stream and send it to the server
- If the password is displayed, the login succeeds. If the password is incorrect, the login fails. Perform the preceding steps again
The first step is to define methods for processing input data
When submitting a button, you first make sure the contents of the two input fields are not empty, and then merge the two strings into one and return them as strings for easy transmission
We define a function called getInputDate() to implement this method, which eventually returns the combined string of the account password (separated by a space), but checks whether the two input fields are null before returning the string, and returns the combined string if they are not:
// Account password input box
public InputField userNameInput;
public InputField passwordInput;
/// <summary>
///Gets the contents of the input box
/// </summary>
public string getInputDate()
{
if(userNameInput.text ! =""&& passwordInput.text ! ="")
{
// Get the text of the input box and strip out the Spaces
string userName = userNameInput.text.Replace(""."");
string password = passwordInput.text.Replace(""."");
// Merge the two strings
string strSend = userName + "" + password;
/ / test
Debug.Log("Merge string:" + strSend);
return strSend;
}
return null;
}
Copy the code
Second, define the method that sends input to the server side
This step is the key to connecting the client to the server, creating a connection using the server connection class you created earlier, and then sending the data to the server
The specific operation details are as follows: Define a function that will be executed step on the returned string (not empty) as arguments, and then to achieve when the first call to this function, use the client Socket Socket connection to the server, in order to achieve the first call only connection, using an if statement for judgment, finally will merge account password forwarded to bytes sent to the server:
//ConnServer defines classes for the connection server in Unity Network Programming 2 (see this article for source code)
private ConnServer connServer;
private Socket socket;
private bool isConn = false;
/// <summary>
///Sends data to the server
/// </summary>
/// <param name="strSend"></param>
public Socket sendDateToServer(string strSend)
{
byte[] bytes=Encoding.UTF8.GetBytes(strSend);
// Create a connection socket the first time the method is called
if (isConn==false)
{
connServer = new ConnServer("127.0.0.1".30000);
socket = connServer.conn();
isConn = true;
}
// Send data to the server
socket.Send(bytes);
Debug.Log("Data sent successfully");
return socket;
}
Copy the code
The third step is to receive the return value after the database has processed the data
When we send the non-empty account password to the server, the server will perform database query, query results are as follows, through enumeration to convert the query results into corresponding strings (we can use a shorter way to transmit the actual application) back to the client, the specific string represents the meaning of:
succes
: Indicates that the account password existsuserNameError
: The query account does not exist, or the user name is incorrectpasswordError
: Indicates that the query account exists but the password does noterror
: This case represents an unknown error and is written as a server connection error
The getReturnDate() method is defined on the client side to receive such a string:
Define parameters, Receive the socket that was previously connected to the server, and then use the Receive() method to Receive the returned byte stream and return it as a string. Use try catch to monitor errors. If the process fails, an error will be returned.
/// <summary>
///Gets the result returned by the server
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public string getReturnDate(Socket socketDemo)
{
byte[] bytes;
string strGet = null;
int maxBuffer = 1024;
byte[] buffer = new byte[maxBuffer];
try
{
int length = socketDemo.Receive(buffer);
strGet = Encoding.UTF8.GetString(buffer, 0, length);
Debug.Log("Received message from server :" + strGet);
return strGet;
}
catch (Exception e)
{
Debug.Log("Failed to get server content: error:" + e.ToString());
}
return "error";
}
Copy the code
Fourth, define methods to handle the results returned by the server
In the third step, we received the database query result returned by the server, which needs to be processed and analyzed on the client side to complete the logical operation on the client side:
- Accept to
succes
: Scenario jump - To receive
userNameError
: Prompt “Error in entering account” - To receive
passwordError
: Prompt “Input password error” - To receive
error
: prompt “server connection error, please try again”
But for testing purposes, uniformly print logs to display query results:
public void showStatus(string strGet)
{
switch(strGet)
{
case "succes":
Debug.Log("Query successful");
break;
case "userNameError":
Debug.Log("Incorrect user name input");
break;
case "passwordError":
Debug.Log("Password input error");
break;
default:
Debug.Log("Server connection error");
break; }}Copy the code
Fifth, define the submit button monitoring event method
This step is to write a method bound to the submit button and execute the previous method to complete all client steps for logging into the system
public void loginButton()
{
// Take a string of input boxes and merge them to return a string
string strSend = getInputDate();
if(strSend ! =null)
{
// If the returned string is not empty, it is sent to the server side
Socket socket = sendDateToServer(strSend);
// Accept the result returned by the server
string strReturn = getReturnDate(socket);
// Process the result returned by the server
showStatus(strReturn);
}
else
{
Debug.Log("Account number or password is empty"); }}Copy the code
Step 6 The login script binds the login button
First, you add the script to the object in the scene. This test selects a new empty object named Scripts, and then drags the script into that object
Second, next you need to drag the script into the required two input fields:
Third, bind the corresponding loginButton() method to the button, which completes the client programming
The server side
Create a script named Login on the server side to implement the Login function
The first step is to obtain the account password sent by the client
Start by creating a function GetReceive() as a receiving method for data sent from the client, and define a socket as a listening method for a socket connected to the server
The Socket receives the byte stream using Receive (), converts it to a string, and returns it
/// <summary>
///Obtain the account password sent by the client
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public string GetReceive(Socket socket)
{
string strGet = null;
int maxBuffer = 1024;
byte[] buffer = new byte[maxBuffer];
try
{
int length = socket.Receive(buffer);
strGet = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine("Received contents :"+strGet);
return strGet;
}
catch (Exception e)
{
Console.WriteLine("Failed to get content: error:" + e.ToString());
}
return null;
}
Copy the code
Step 2 query the database account password
Database query first need to connect to the database, in “Unity network programming two “in some of the database connection class ConnDB, here will be directly called, if you do not understand, you can view the previous article
- First create the function
FindDate()
And accepts a string parameter, that is, the parameter received from the client. After receiving the parameter, the string needs to be processed first, because the string is a combination of the account and password and needs to be usedSplit()
Method to decompose it- After obtaining the account, pass
MySqlCommand()
Run the SQL command to query information using the account, and pass theExecuteReader()
The query data is obtained and the password is obtained- A series of judgments, and a comparison of the queried password with the password sent from the client, and the result, so that the series of results (expressed as a string) can be returned
The structure of the Login table in the database is:
The specific code is:
// Enter the parameters needed for the connection string
private string hostDB = "localhost";
private string portDB = "3306";
private string userDB = "root";
private string passwordDB = ""; // The database password is not displayed
private string dateNameDB = "day05";
/// <summary>
///Query the database to see if the string exists
/// </summary>
/// <param name="strGet"></param>
/// <returns></returns>
private string FindDate(string strGet)
{
if(strGet==null)
{
Console.WriteLine("Get server string is empty");
return "null";
}
// Process the entered account password string
string[] strGets = strGet.Split("");
string userName = strGets[0];
string password = strGets[1];
// Create the SQL language and execute the query
try
{
ConnDB connDB = new ConnDB(hostDB, portDB, userDB, passwordDB, dateNameDB);
MySqlConnection conn = connDB.openDate();
string sql = string.Format("select * from Login where username=\"{0}\"", userName);
MySqlCommand cmd = new MySqlCommand(sql, conn);
// Read the result of the query
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read()) // Check whether the query result is null
{
if(reader[1].Equals(password))
{
Console.WriteLine("Account password found successfully");
return "succes";
}
else
{
Console.WriteLine("Query result available, but different from input, short input password error");
return "passwordError"; }}else
{
Console.WriteLine("Query is empty, account does not exist");
return "userNameError";
}
}
catch (Exception e)
{
Console.WriteLine("Database connection error:"+e.ToString());
}
Console.WriteLine("Error in query process");
return "error";
}
Copy the code
Third, return the result to the client
This step is to return the results of the database query to the connected client, the code is simple, directly watch can:
/// <summary>
///Return the query result to the client
/// </summary>
private void SendDate(Socket socket,string strSend)
{
byte[] bytes = Encoding.UTF8.GetBytes(strSend);
socket.Send(bytes);
}
Copy the code
Fourth, call the method in the constructor of the function
The first thing you need to do is create a socket, which is the socket for the server. Here the world uses the previous Unity Network Programming 1 class to create a server to create a socket and start it
After the startup is complete, we need to use Accept() to monitor the socket of the connection, and use a loop to monitor the data sent by the client and do a series of processing before returning:
// The server address and port number used to create the socket connection
private string ip = "127.0.0.1";
private int port = 30000;
/// <summary>
///It is convenient to perform related operations directly at instantiation time
/// </summary>
public LogIn()
{
CreateServer server = new CreateServer(ip, port);
Socket socket = server.StartSocket();
Socket clider = socket.Accept();
while (true)
{
string strGet = GetReceive(clider);
stringstrSend = FindDate(strGet); Console.WriteLine(strSend); SendDate(clider, strSend); }}Copy the code
Fifth, instantiate the login class in the main function and test it
We simply instantiate login in the Main() function, and then start the project. We also start the project in the Unity client, and then enter the account password to test if the program is running correctly
conclusion
To realize the data exchange between the front and back ends through Socket, the data needs to be sent and received on the client side and the server side respectively. At the same time, the client side processes the logic of the client side, while the server side processes the logic of the server side. This advantage is to reduce the amount of data transmission