Unity如何使用NetworkDiscovery从客户端查找服务器

时间:2016-07-30 16:42:58

标签: c# networking unity3d client-server

[我在c#工作]

为了确定天气,设备应该成为仅具有本地客户端或客户端的服务器(对于无主服务器的网络),我需要先找出该设备是否还有其他可用服务器,然后再转换为服务器本地客户端,如果没有通过从服务器接收NetworkDiscovery广播来加入另一个客户端设备 - 目前我无法让客户端从服务器接收广播。

我创建了两个空的游戏对象,每个都有脚本,一个脚本使其成为服务器,应该通过NetworkDiscovery.StartAsServer()通过NetworkDiscovery进行广播,但目前我的客户NetworkDiscovery.StartAsClient()已经设置了到OnRecievedBroadcast()没有得到被调用的using UnityEngine; using System.Collections; using UnityEngine.Networking; public class SearchForServers : MonoBehaviour { bool serverIsFound; NetworkDiscovery NetworkDiscovery; // Use this for initialization void Start () { serverIsFound = false; NetworkClient Client = new NetworkClient(); NetworkDiscovery = gameObject.AddComponent<NetworkDiscovery>(); NetworkDiscovery.Initialize(); NetworkDiscovery.StartAsClient(); } void OnRecievedBroadcast(string fromAdress, string data) { serverIsFound = true; } // Update is called once per frame void Update () { Debug.Log("Server Found = " + serverIsFound); } } 函数,因此没有从服务器接收广播。

下面显示的两个脚本是客户端和服务器:

客户 -

    using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class CreateServer : MonoBehaviour
{
    bool create;
    int minPort = 10000;
    int maxPort = 10010;
    int defaultPort = 10000;
    NetworkDiscovery NetworkDiscovery;

    void Start()
    {
        create = true;
        if (create == true)
        {
            int serverPort = createServer();
            if (serverPort != -1)
            {
                Debug.Log("Server created on port : " + serverPort);
            }
            else
            {
                Debug.Log("Failed to create Server");
            }
        }
        NetworkDiscovery = gameObject.AddComponent<NetworkDiscovery>();
        NetworkDiscovery.Initialize();
        NetworkDiscovery.StartAsServer();
    }


    //Creates a server then returns the port the server is created with. Returns -1 if server is not created
    int createServer()
    {
        int serverPort = -1;
        //Connect to default port

      bool serverCreated = NetworkServer.Listen(defaultPort);
        if (serverCreated)
        {
            serverPort = defaultPort;
            Debug.Log("Server Created with default port");
        }
        else
        {
            Debug.Log("Failed to create with the default port");
            //Try to create server with other port from min to max except the default port which we trid already
            for (int tempPort = minPort; tempPort <= maxPort; tempPort++)
            {
                //Skip the default port since we have already tried it
                if (tempPort != defaultPort)
                {
                    //Exit loop if successfully create a server
                    if (NetworkServer.Listen(tempPort))
                    {
                        serverPort = tempPort;
                        break;
                    }

                    //If this is the max port and server is not still created, show, failed to create server error
                    if (tempPort == maxPort)
                    {
                        Debug.LogError("Failed to create server");
                    }
                }
            }
        }
        return serverPort;
    }
}

服务器 -

@objects = Object.near(location, 50)

这些是带有调试日志记录的控制台日志

enter image description here

感谢您阅读我希望您能够意识到我哪里出错或者确实如何完成所述任务。 @Programmer

1 个答案:

答案 0 :(得分:3)

首先,您将每个服务器和客户端脚本命名为相同的名称。您在服务器代码中不需要OnRecievedBroadcast。您只需要在客户端代码中使用它。由于您没有覆盖OnRecievedBroadcast,因此未在客户端调用NetworkDiscovery。你必须覆盖它。

以下是一个简单的发现代码

<强>客户端

public class NetClient : NetworkDiscovery
{

    void Start()
    {
        startClient();
    }

    public void startClient()
    {
        Initialize();
        StartAsClient();
    }

    public override void OnReceivedBroadcast(string fromAddress, string data)
    {
         Debug.Log("Server Found");
    }
}

服务器

public class NetServer : NetworkDiscovery
{
    // Use this for initialization
    void Start()
    {
        Application.runInBackground = true;
        startServer();
    }

    //Call to create a server
    public void startServer()
    {
        int serverPort = createServer();
        if (serverPort != -1)
        {
            Debug.Log("Server created on port : " + serverPort);
            broadcastData = serverPort.ToString();
            Initialize();
            StartAsServer();
        }
        else
        {
            Debug.Log("Failed to create Server");
        }
    }

int minPort = 10000;
int maxPort = 10010;
int defaultPort = 10000;

//Creates a server then returns the port the server is created with. Returns -1 if server is not created
private int createServer()
{
    int serverPort = -1;
    //Connect to default port
    bool serverCreated = NetworkServer.Listen(defaultPort);
    if (serverCreated)
    {
        serverPort = defaultPort;
        Debug.Log("Server Created with deafault port");
    }
    else
    {
        Debug.Log("Failed to create with the default port");
        //Try to create server with other port from min to max except the default port which we trid already
        for (int tempPort = minPort; tempPort <= maxPort; tempPort++)
        {
            //Skip the default port since we have already tried it
            if (tempPort != defaultPort)
            {
                //Exit loop if successfully create a server
                if (NetworkServer.Listen(tempPort))
                {
                    serverPort = tempPort;
                    break;
                }

                //If this is the max port and server is not still created, show, failed to create server error
                if (tempPort == maxPort)
                {
                    Debug.LogError("Failed to create server");
                }
            }
        }
    }
    return serverPort;
}
}

createServer()函数是您上一个问题的函数。我不认为您可以在编辑器中同时运行服务器和客户端代码。

为了进行测试,您必须在您的电脑上构建代码并启用服务器代码/ NetServer。运行构建的程序然后从编辑器运行客户端/ NetClient代码。这应该在服务器上发现游戏。