unity UDP 接收消息解析Json对象

UDP的优势

UDP通信的优势在于不要求对方强制在线,没有因为网络连接不顺畅或连接失败导致的卡顿问题;缺点也是因为不能判断对方是否在线,导致整个连接不可靠,需要通过自定义代码来进行反馈。

话不多说直接上代码:

​
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using System.Collections.Concurrent;
using System.Collections;
    public class UDPRecvice : MonoBehaviour
    {
        public string ip;

        public int port;

        private string receiveString;

        private UdpClient UdpClient;

        private IPEndPoint UDP_IPEndPoint;

        private byte[] data = new byte[1024];

        private ConcurrentQueue<string> queue;

        private IAsyncResult asyncResult;

        private void Start()
        {
            ip = 需要接收的IP;
            port = 需要接收的端口号;
            UdpClient = new UdpClient(port);
            UDP_IPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            //安全队列
            queue = new ConcurrentQueue<string>();
            StartCoroutine(ReceiveAsync());
        }
        
        private void Update()
        {
            //解析数据
            queue.TryDequeue(out receiveString);
            //以下为示例          
            try
            {
            returnData data = JsonUtility.FromJson<returnData>(receiveString);
            if(data.code ==200)
             {
              Debug.Log("成功");
             }
            }
            catch (Exception)
            {
                throw;
            }
        }

        [Serializable]
        public class returnData
        {
         public int code;
        }

        #region 异步
        private IEnumerator ReceiveAsync()
        {
            for (; ; )
            {
                if (UdpClient.Available>0)
                {
                    //异步接收UDP数据
                    asyncResult = UdpClient.BeginReceive(null, null);
                    yield return new WaitUntil(() => asyncResult.IsCompleted);
                    //结束接收并获取数据
                    try
                    {
                        data = UdpClient.EndReceive(asyncResult, ref UDP_IPEndPoint);
                        queue.Enqueue(Encoding.UTF8.GetString(data));
                    }
                    catch (Exception ex)
                    {
                    }
                    
                }
                yield return null;
            }    
        }
        #endregion

        private void OnApplicationQuit()
        {
            this.SocketQuit();
        }

        private void OnDestroy()
        {
            this.SocketQuit();
        }

        private void SocketQuit()
        {
            StopAllCoroutines();
            this.UdpClient.Close();            
        }

    }

​

需要注意的是:必须在实体类前加上[Serializable],否则对于嵌套对象无法正确接收

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值