Application udp-unity

Rompre

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine.UI;
public delegate void Extrued_action_del(Data_Parsing data);
public class Sever_Udp : MonoBehaviour
{
    private Socket _server;
    private string _ip;
    private int _port = 10000;
    private EndPoint endPointRef;
    Thread _receiveClientMsg;

    public static event Extrued_action_del Extrued_action_eve;
    Data_Parsing data_Parsing;
    string  msg;
    bool msg_to;
    private void Start()
    {
        _ip = GetTpv4(NetworkInterfaceType.Ethernet).ToString();
        StartUp();
    }
    private void Update()
    {
        if (msg!=null&& msg_to == true)
        {
            print("SADASD");
            //分发消息
            Extrued_action_eve?.Invoke(data_Parsing);
            msg_to = false;
        }
    }
    public void StartUp()
    {
        //建立套接字
        _server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        EndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);

        _server.Bind(endPoint);
        endPointRef = new IPEndPoint(IPAddress.Any, 0);

        _receiveClientMsg = new Thread(ReceiveClientMsg);
        _receiveClientMsg.Start();

    }
    bool stop;
    public void ReceiveClientMsg()
    {
        byte[] msgBytes = new byte[1024 * 64];
        while (true)
        {
            int len = _server.ReceiveFrom(msgBytes, ref endPointRef);
            string str = Encoding.UTF8.GetString(msgBytes, 0, len);

            IPEndPoint clientEndPoint = endPointRef as IPEndPoint;
            //解析
            Extrued_Message(str);

            if (stop)
            {
                break;
            }
            Send("已收到", endPointRef);
        }
       
        if (_receiveClientMsg.ThreadState == ThreadState.Running|| _receiveClientMsg!=null)
        {
           
            _receiveClientMsg.Interrupt();
            _receiveClientMsg.Abort();
            _server.Close();
        }
    }
    public void Send(string str, EndPoint target)
    {
        _server.SendTo(Encoding.UTF8.GetBytes(str), target);
    }
    void Extrued_Message(string json)
    {
        if (msg != json)
        {
            msg = json;
            try
            {
                data_Parsing = JsonConvert.DeserializeObject<Data_Parsing>(msg);

                msg_to = true;
            }
            catch (Exception e)
            {

                print(e);
            }   
        }
       
       
    }
    private void OnDestroy()
    {
        stop = true;
        if (_receiveClientMsg.ThreadState == ThreadState.Running || _receiveClientMsg != null)
        {
            print("关闭服务器");
            _receiveClientMsg.Interrupt();
            _receiveClientMsg.Abort();
            _server.Close();
        }
    }
    private void OnApplicationQuit()
    {
        stop = true;
        if (_receiveClientMsg.ThreadState == ThreadState.Running || _receiveClientMsg != null)
        {
            print("关闭服务器");
            _receiveClientMsg.Interrupt();
            _receiveClientMsg.Abort();
            _server.Close();
        }
    }
    //获取IP地址
    public IPAddress GetTpv4(NetworkInterfaceType type)
    {
        NetworkInterface[] networkinterface = NetworkInterface.GetAllNetworkInterfaces();
        for (int i = 0; i < networkinterface.Length; i++)
        {
            Console.WriteLine(networkinterface[i].Name + "------" + networkinterface[i].ToString());

            //无线网操作
            if (type == networkinterface[i].NetworkInterfaceType && networkinterface[i].OperationalStatus == OperationalStatus.Up)
            {
                UnicastIPAddressInformationCollection ips = networkinterface[i].GetIPProperties().UnicastAddresses;
                foreach (UnicastIPAddressInformation item in ips)
                {
                    if (item.Address.AddressFamily == AddressFamily.InterNetwork)
                    {

                        return item.Address;
                    }
                }
            }
        }
        return null;
    }
}
#region 数据
public struct Data_Parsing
{

    public string audio_name;
    public bool audio_;//是否开启语音导航 true= play | false =stop
    public bool audio_pause;//true= pause| false= unpause
    public bool audio_mute;//mute=true| mute=false
    public bool audio_volum;//true=放大音量 false=缩小音量

    public int index;//当前窗口Id

    public string type;//视频、网页投屏、PPT、图片
    public bool big_small;//true 放大 false 缩小

    //视频
    public string video_path;//视频路径 
    public bool video_volume;//调节音量  true 放大 false 缩小
    public bool video_play;//true 为play false 为stop
    public bool video_pause;//pause
    //网页投屏
    public string ip;//Sever Ip 
    public ushort port_sever;//Sever port 
    public ushort port_client;//Sever port 
    //PPt
    public string ppt_path;//Sever port 
    public bool ppt_change_index;//当前页数 true 下一页 false 上一页
    //图片
    public string tex_name;//例如Default.jpg  切记加后缀
}
#endregion


 Client

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using UnityEngine;
public class Client_Udp : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    private Socket _client;
    //服务器地址
    private string _ipSerer = "192.168.30.28";
    //客户端地址
    private string _ipClient = "192.168.30.28";

    private int _port = 10000;
    private int _port1 = 10001;
    private EndPoint _serverEndPoint;
    private EndPoint _clientEndPoint;
    public void StartUp()
    {
        //建立套接字
        _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //配置服务器网络标识
        _serverEndPoint = new IPEndPoint(IPAddress.Parse(_ipSerer), _port);
        // //配置客户端网络标识
        _clientEndPoint = new IPEndPoint(IPAddress.Parse(_ipClient), _port1);

        _client.Bind(_clientEndPoint);

        Thread _receiveServerMsg = new Thread(ReceiveServerMsg);
        _receiveServerMsg.Start();
    }
    public void Send(string str)
    {
        _client.SendTo(Encoding.UTF8.GetBytes(str), _serverEndPoint);
    }
    public void ReceiveServerMsg()
    {
        while (true)
        {
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] msgBytes = new byte[1024 * 64];

            int len = _client.ReceiveFrom(msgBytes, ref endPoint);
            string str = Encoding.UTF8.GetString(msgBytes, 0, len);

            IPEndPoint clientEndPoint = endPoint as IPEndPoint;
            Console.WriteLine("Receive{0}:{1}:{2}", clientEndPoint.Address.ToString(), clientEndPoint.Port, str);
        }

    }
}

Guess you like

Origin blog.csdn.net/fanfan_hongyun/article/details/128066391