Unity 如何使用 NetworkDiscovery 从客户端查找服务器 [英] Unity how to find a server from client using NetworkDiscovery

查看:42
本文介绍了Unity 如何使用 NetworkDiscovery 从客户端查找服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[我在 c# 工作]

为了决定天气,设备应该成为具有本地客户端或单独客户端的服务器(对于无主服务器网络),我需要在变成具有以下功能的服务器之前找出该设备是否还有其他可用的服务器本地客户端,如果不是通过从服务器接收 NetworkDiscovery 广播或不接收其他客户端设备加入 - 目前我无法让客户端从服务器接收广播.

In order to decide weather a device should become a server with local client or client alone (for main-server-less networking) I need to find out if there are any other available servers for that device before turning into a server with local client if not for another client device to join by either receiving NetworkDiscovery broadcasts from a server or not - currently I can't get a client to receive broadcast from a server.

我创建了两个空游戏对象,每个游戏对象都带有脚本,一个脚本使它成为服务器,应该通过 NetworkDiscovery.StartAsServer() 从它的 NetworkDiscovery 广播,但目前我的一个NetworkDiscovery 已设置为 NetworkDiscovery.StartAsClient() 的客户端未调用 OnRecievedBroadcast() 函数,因此未从服务器接收广播.

I have created two empty gameobjects each with scripts, one script makes it a server and should be broadcasting from its NetworkDiscovery via NetworkDiscovery.StartAsServer() but currently one my client whose NetworkDiscovery has been set to NetworkDiscovery.StartAsClient() is not getting theOnRecievedBroadcast() function called hence not receiving broadcasts from the server.

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

The two scripts shown below are the client and server:

客户 -

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;
    }
}

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

These are the console logs with the debug logging

感谢您的阅读,我希望您能意识到我哪里出错了,或者确实如何以其他方式完成上述任务.@程序员

Thanks for reading I hope that you can realise where I have gone wrong or indeed how to complete said task otherwise. @Programmer

推荐答案

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

First of all you named each server and client script the-same name. You don't need OnRecievedBroadcast in the server code. You only need it in the client code. OnRecievedBroadcast is not being called on the client side because you did not override NetworkDiscovery. You must override it.

这是一个简单的发现代码:

客户:

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() 函数是您上一个问题中的一个函数.我认为您不能在编辑器中同时运行服务器和客户端代码.

The createServer() function is a function from your last question. I don't think you can have both server and client code running at the-same time in the Editor.

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

For testing, you must build the code in your pc with the server code/NetServer enabled. Run the built program then from your Editor you can run the client/NetClient code. This should discover game on the server.

这篇关于Unity 如何使用 NetworkDiscovery 从客户端查找服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆