域网广播

using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using UnityEngine;
using System;

public class UDPBroadCast : MonoBehaviour
{
    private UdpClient UDPrecv;

    private void Start()
    {
        UDPrecv = new UdpClient();
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        socket.Bind(new IPEndPoint(IPAddress.Any, 9999));
        UDPrecv.Client = socket;

        UDPrecv.BeginReceive(ReceiveCallback, null);
    }

    public void Broad(string mes)
    {
        UdpClient UDPsend = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 9999);
        byte[] message = Encoding.UTF8.GetBytes(mes);
        UDPsend.Send(message, message.Length, endpoint);
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        IPEndPoint endpoint = null;
        byte[] recvBuf = UDPrecv.EndReceive(ar, ref endpoint);
        string msg = Encoding.UTF8.GetString(recvBuf);
        //TypeEventSystem.Send(new OnRecvBroadcast(msg));
        Debug.Log("收到" + endpoint.Address + "的广播消息:" + msg);//收到广播后打印一下,需要需要注意的是这个是子线程,需要UI等操作需要自己转到主线程
        UDPrecv.BeginReceive(new AsyncCallback(ReceiveCallback), null);//收到信息后继续开始接受信息
    }
}