preface

After we complete the server and database connection, it is necessary to realize the client for the server connection function

3.1 the client connects to the server

1, first create a client connection script, in the script to connect to the server, also need to use Socket to design the connection mode

2. In the script, we first need to use the constructor to get the server address IP and port number port

3. Select and configure the connection protocol and data transmission mode as required

4, then define a method to Connect to the specified server side through the Connect() method in the Socket

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

public class ConnServer
{
    private Socket socket;
    private IPEndPoint ipe;
    // The IP address and port number must be the same as those on the server
    private string ip;
    private int port;
    public ConnServer(string _ip,int _port)
    {
        this.ip = _ip;
        this.port = _port;
    }
    public Socket conn()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ipe = new IPEndPoint(IPAddress.Parse(ip), port);
        //Connect() is the method to Connect to the server
        socket.Connect(ipe);
        returnsocket; }}Copy the code

Through the code can be seen that the use of Socket whether client or server to create a connection are basically the same, the important parameters of the two connection is the IP address and port port, and the specific connection, protocol and other Socket has helped us to encapsulate, we just need to call the method

3.2. Test whether the connection is successful

First create and run the Test script, attach the script to the scene object, and then write the Test script:

Trigger a server connection event by listening for the space bar on the keyboard button:

using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public class Test : MonoBehaviour
{
    ConnServer connServer;

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            connServer = new ConnServer("127.0.0.1".30000); Socket socket= connServer.conn(); }}}Copy the code

Before the official start, you need to start the server built before, and then execute the program in Unity. If “Connecting to the server succeeded” is displayed in the log, the server is successfully connected.

conclusion

The Unity client connects to the server. The basic structure is similar to that of the server. It needs to be noted that the IP address and port number must be consistent