92 lines
2.5 KiB
C#
92 lines
2.5 KiB
C#
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()
|
|
{
|
|
udpClient = new UdpClient();
|
|
udpClient.EnableBroadcast = true;
|
|
|
|
// 启动广播线程
|
|
broadcastThread = new Thread(BroadcastIP);
|
|
broadcastThread.Start();
|
|
Debug.Log("广播服务器已启动");
|
|
}
|
|
|
|
// 广播显示端服务器的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, 8887);
|
|
|
|
while (isRunning)
|
|
{
|
|
try
|
|
{
|
|
udpClient.Send(data, data.Length, endPoint);
|
|
Debug.Log($"广播IP: {message}");
|
|
Thread.Sleep(1000); // 每秒广播一次
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"广播错误: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
// 获取本地IP地址
|
|
private string GetLocalIPAddress()
|
|
{
|
|
try
|
|
{
|
|
foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
|
|
{
|
|
if (networkInterface.OperationalStatus == OperationalStatus.Up)
|
|
{
|
|
foreach (var unicastIPAddress in networkInterface.GetIPProperties().UnicastAddresses)
|
|
{
|
|
if (unicastIPAddress.Address.AddressFamily == AddressFamily.InterNetwork)
|
|
{
|
|
return unicastIPAddress.Address.ToString();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"获取IP地址错误: {ex.Message}");
|
|
}
|
|
return "";
|
|
}
|
|
|
|
// 应用程序退出时清理资源
|
|
private void OnApplicationQuit()
|
|
{
|
|
isRunning = false;
|
|
udpClient?.Close();
|
|
if (broadcastThread != null && broadcastThread.IsAlive)
|
|
{
|
|
broadcastThread.Join(1000); // 等待线程结束
|
|
}
|
|
}
|
|
} |