AnimalSimulation/Assets/Scripts/BroadcastServer.cs

108 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class BroadcastServer : MonoBehaviour
{
private UdpClient udpClient; // 用于发送广播的UDP客户端
private Thread broadcastThread; // 广播线程
private volatile bool isRunning = true; // 线程安全的运行标志
// 脚本启动时调用
void Start()
{
try
{
udpClient = new UdpClient();
udpClient.EnableBroadcast = true;
// 启动广播线程
broadcastThread = new Thread(BroadcastIP);
broadcastThread.Start();
Debug.Log("广播服务器已启动,端口: 9999");
}
catch (Exception ex)
{
Debug.LogError($"初始化UDP客户端失败: {ex.Message}");
}
}
// 广播显示端服务器的IP地址
private void BroadcastIP()
{
string localIP = GetLocalIPAddress();
if (string.IsNullOrEmpty(localIP))
{
Debug.LogError("无法获取本地IP地址广播停止");
return;
}
string message = $"ServerIP:{localIP}";
byte[] data = Encoding.UTF8.GetBytes(message);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 9999); // 修改为9999
while (isRunning)
{
try
{
udpClient.Send(data, data.Length, endPoint);
Debug.Log($"广播IP: {message}");
Thread.Sleep(1000); // 每秒广播一次
}
catch (Exception ex)
{
Debug.LogError($"广播错误: {ex.Message}");
Thread.Sleep(5000); // 出错后等待5秒重试
}
}
}
// 获取本地IP地址排除回环地址
private string GetLocalIPAddress()
{
try
{
foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up &&
networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
foreach (var unicastIPAddress in networkInterface.GetIPProperties().UnicastAddresses)
{
if (unicastIPAddress.Address.AddressFamily == AddressFamily.InterNetwork)
{
string ip = unicastIPAddress.Address.ToString();
if (!ip.StartsWith("127."))
{
Debug.Log($"选择IP: {ip} (接口: {networkInterface.Name})");
return ip;
}
}
}
}
}
Debug.LogError("未找到有效的IPv4地址");
return "";
}
catch (Exception ex)
{
Debug.LogError($"获取IP地址错误: {ex.Message}");
return "";
}
}
// 应用程序退出时清理资源
private void OnApplicationQuit()
{
isRunning = false;
udpClient?.Close();
if (broadcastThread != null && broadcastThread.IsAlive)
{
broadcastThread.Join(1000); // 等待线程结束
}
Debug.Log("广播服务器已停止");
}
}