zoukankan      html  css  js  c++  java
  • 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);
        }
    }

    个人笔记 欢迎指正

  • 相关阅读:
    运行hexo提示/usr/bin/env: node: 没有那个文件或目录
    安装cuda时 提示toolkit installation failed using unsupported compiler解决方法
    使用caffe自动测试模型top5的结果
    配置caffe的python环境时make pycaffe提示fatal error: numpy/arrayobject.h No such file or directory解决方法
    error: library dfftpack has Fortran sources but no Fortran compiler found解决方法
    ubuntu硬盘安装卡在探测文件系统
    win7+ubuntu双系统中卸载ubuntu方法
    深度学习入门教程UFLDL学习实验笔记三:主成分分析PCA与白化whitening
    深度学习入门教程UFLDL学习实验笔记二:使用向量化对MNIST数据集做稀疏自编码
    深度学习入门教程UFLDL学习实验笔记一:稀疏自编码器
  • 原文地址:https://www.cnblogs.com/Roz-001/p/12106600.html
Copyright © 2011-2022 走看看