首先设置ini文件——》新建txt将文件后缀名改为.ini (l利用INIParse读取)
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine.UI; using System; public class UDPCilent : MonoBehaviour { #region 单例模式 private static UDPCilent instance; public static UDPCilent Instance { get { if (instance==null) { instance = GameObject.Find("UDP").gameObject.GetComponent<UDPCilent>(); } return instance; } } #endregion private UdpClient client; private static IPEndPoint endPoint; private Thread reciveThread; private UdpClient Udprecive; public List<string> msgList; public Text MessageText; public INIParser ini; // Start is called before the first frame update void Awake() { client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); endPoint = new IPEndPoint(IPAddress.Broadcast, 9999);//Broadcast提供IP广播地址 } void Start() { reciveThread = new Thread(new ThreadStart(ReciveThread)); reciveThread.IsBackground = true; reciveThread.Start(); } // Update is called once per frame void Update() { if (msgList.Count > 0) { MessageText.text = msgList[0]; INIParser ReciveIni = new INIParser(); ReciveIni.Open(Application.dataPath + @"/Config.ini"); ReciveIni.WriteValue("Other", DateTime.Now.ToString(), msgList[0]); ReciveIni.Close(); msgList.RemoveAt(0); } } /// <summary> /// 广播数据(发送消息) /// </summary> /// <param name="message"></param> public void SendUPDMessage(string message) { byte[] buff = Encoding.Default.GetBytes(message); client.Send(buff, buff.Length, endPoint); } /// <summary> /// 接收消息 /// </summary> void ReciveThread() { Udprecive = new UdpClient(new IPEndPoint(IPAddress.Any, 9998)); IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any,0); while (true) { byte [] buff= Udprecive.Receive(ref iPEndPoint); string Message = Encoding.UTF8.GetString(buff); //此处不能让消息框内容=message,而应该新建一个List,让消息存入List然后判断List来读取消息(同理此处不应该ini存入) msgList.Add(Message); } } }