unity 作为客户端查询 局域网里面所有的服务端,并打印所有的服务端ip,端口8080
时间: 2024-04-14 17:29:19 浏览: 72
您好!您可以使用Unity的NetworkDiscovery组件来查询局域网中的服务端。以下是一个示例代码,用于查询局域网中的服务端并打印它们的IP和端口:
```csharp
using UnityEngine;
using UnityEngine.Networking;
public class ServerDiscovery : MonoBehaviour
{
public int broadcastPort = 8080;
public int broadcastKey = 8888;
public float broadcastInterval = 1f;
private NetworkDiscovery networkDiscovery;
void Start()
{
networkDiscovery = GetComponent<NetworkDiscovery>();
networkDiscovery.Initialize();
networkDiscovery.broadcastPort = broadcastPort;
networkDiscovery.broadcastKey = broadcastKey;
InvokeRepeating("BroadcastServer", 0f, broadcastInterval);
}
void BroadcastServer()
{
networkDiscovery.StartAsClient();
}
void OnReceivedBroadcast(string fromAddress, string data)
{
Debug.Log("Server discovered: " + fromAddress);
// 解析fromAddress中的IP和端口
string[] addressParts = fromAddress.Split(':');
string ip = addressParts[3].Trim();
int port = int.Parse(addressParts[4].Trim());
if (port == 8080)
{
Debug.Log("Server IP: " + ip + ", Port: " + port);
}
}
}
```
将上述代码添加到一个空的GameObject上,并将其作为客户端运行时,它将每秒钟向局域网广播一次,并在发现服务端时打印其IP和端口。请确保您已经添加了NetworkDiscovery组件,并将其相关参数设置为所需的值。
希望这可以帮助到您!如果还有其他问题,请随时提问。