unity_Socket_UDP广播协议的接收发送(客户端模块)

Posted roz-001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity_Socket_UDP广播协议的接收发送(客户端模块)相关的知识,希望对你有一定的参考价值。

接收Socket_UDP广播机制的客户端实现,不多说直接上代码:

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

//
using System.Xml;


public class Lighthouse : MonoBehaviour
{
    private byte[] data;
    private string Error_Message;
    private Thread thread;
    private EndPoint ep;
    private bool IsStop = false;
    private Socket socket;
    private int udpPort = 9090;
    public static Lighthouse instance;

    // 消息回调
    private static string m_callMessage = string.Empty;
    private bool m_isTCP = true;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            //
            // GetSeverIP();
            //DontDestroyOnLoad(gameObject);
        }
        //else
        //{
        //    Destroy(gameObject);
        //}

        //
        m_isTCP = true;
    }


    private void Update()
    {
        if (m_isTCP)
        {
            if (!string.IsNullOrEmpty(m_callMessage))
            {
                this.SendUDP_SceneInfo();
                // 建立TCP连接
                Client._Instance.StartConnect(this.Analyse_XMLIP());
                //
                m_isTCP = false;
            }
        }
    }


    public void GetSeverIP()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            ep = new IPEndPoint(IPAddress.Any, udpPort);
            socket.Bind(ep);
            data = new byte[1024];
            thread = new Thread(Receive);
            thread.IsBackground = true;
            thread.Start();
        }
        catch (Exception e)
        {
            Debug.LogError("错误信息:" + e.Message);
        }

    }

    public void StopReceive()
    {
        IsStop = true;
        thread.Abort();
    }

    private void Receive()
    {
        while (!IsStop)
        {
            if (socket.Available <= 0) continue;
            int recv = socket.ReceiveFrom(data, ref ep);
            string msg = Encoding.ASCII.GetString(data, 0, recv);
            // Debug.Log("接收消息:" + msg);
            Debug.Log("[UDP+接收消息]" + msg);

            //
            m_callMessage = string.Empty;
            m_callMessage = msg;
            //测试
            //if(recv > 0)
            //{
            //    Send(msg);
            //}
            //Thread.Sleep(100);
        }
    }


    public void Send(string msg)
    {
        //msg = "客户端消息:66666666666";
        Debug.Log("[UPD+发送消息]" + msg);


        data = Encoding.UTF8.GetBytes(msg);
        try
        {
            socket.SendTo(data, ep);
        }
        catch (Exception ex)
        {
            Debug.Log("错误信息" + ex.Message);
        }
    }


    public void OnApplicationQuit()
    {
        if (socket != null)
        {
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
        IsStop = true;
        thread.Abort();
    }

    //信息_ID_场景_0或回调信息
    // 发送UDP数据
    private void SendUDP_SceneInfo()
    {
        UDPMessage um = new UDPMessage(MessageType.Register,0,"故宫","0");
        //
        Send(um.ToString());
    }


    // 解析xml中的ip地址
    private string Analyse_XMLIP()
    {
        //
        string strUrl = "D:/LUYOU_File/Msg/addressInfo.xml";
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(strUrl);
        //
        if (xmlDoc!=null)
        {
            XmlElement node=(XmlElement)xmlDoc.SelectSingleNode("address/ip");
            return node.InnerText.Trim();
        }
        return null;
    }
}

public class UDPMessage {

    private MessageType msgType;
    private int PlayerID;
    private string strSceneName;
    private string strCallMessage;

    public UDPMessage(MessageType type,int id,string sceneName,string callMessage)
    {
        this.msgType = type;
        this.PlayerID = id;
        this.strSceneName = sceneName;
        this.strCallMessage = callMessage;
    }

    public override string ToString()
    {
        return string.Format("{0}_{1}_{2}_{3}#",(int)msgType,PlayerID,strSceneName,strCallMessage);
    }
}

 

个人笔记 欢迎指正

以上是关于unity_Socket_UDP广播协议的接收发送(客户端模块)的主要内容,如果未能解决你的问题,请参考以下文章

PHP进阶-网络编程基础概念

Android 使用udp发送广播

Android入门:广播发送者与广播接收者

Android系统广播(Broadcast)注册,发送,接收流程解析

发送UDP广播,接收多条消息

如何将结果数据从广播接收器发送到活动