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],否则对于嵌套对象无法正确接收