Unity UDP异步通信
作者:互联网
UDP异步通信发送字符串案例
发送端脚本:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class Send : MonoBehaviour
{
[SerializeField] private string CustomIp="192.168.0.0";//发送至IP地址
private static string GuDingIp;
public static string guDingIp
{
get
{
return GuDingIp;
}
set
{
SendIPEnd = new IPEndPoint(IPAddress.Parse(GuDingIp = value), 1314);
}
}
private static IPEndPoint SendIPEnd;
private byte[] sendData;
private void Start()
{
if (SendIPEnd == null)
SendIPEnd = new IPEndPoint(IPAddress.Parse(CustomIp), 1314);
}
/// <summary>
///调用此方法发送字符串给 CustomIP
/// </summary>
/// <param name="msg"></param>
public void _____Send(string msg)
{
if (guDingIp == null)
return;
sendData = Encoding.Default.GetBytes(msg);
UdpClient u = new UdpClient(1315);
u.BeginSend(sendData, sendData.Length, SendIPEnd, new AsyncCallback(SendCallback), u);
}
private void SendCallback(IAsyncResult result)
{
UdpClient u = (UdpClient)result.AsyncState;
}
}
接收端脚本:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class Reception : MonoBehaviour
{
private static UdpClient u;
private void Start()
{
___JieShou();
}
private void ___JieShou()
{
if (u == null)
u = new UdpClient(new IPEndPoint(IPAddress.Any, 1314));
u.BeginReceive(new AsyncCallback(ReceiveCallback), u);
}
public void ReceiveCallback(IAsyncResult result)
{
UdpClient u = (UdpClient)result.AsyncState;
IPEndPoint p = new IPEndPoint(IPAddress.Any, 1314);
byte[] recvData = u.EndReceive(result, ref p);
dataContent = Encoding.Default.GetString(recvData);
Thread.Sleep(10);
u.BeginReceive(new AsyncCallback(ReceiveCallback), u);
}
//如果有数据发来,haveData的布尔值就为True;通过实时判断haveData的布尔值,为Ture时改为False然后同时来获取String;
public static bool haveData;
public static string dataContent
{
get
{
return DataContent;
}
set
{
DataContent = value;
haveData = true;
}
}
private static string DataContent;
//P——————————————————————————————————————————————————————————
//实时接收字符串
private void Update()
{
if (haveData)
{
haveData = false;
CheckDataContent(dataContent);
}
}
//接收到字符串并打印
private void CheckDataContent(string str)
{
print(str);
}
}
Unity两个脚本对应两个程序,可以跨平台使用。
标签:异步,UDP,UdpClient,void,System,private,Unity,new,using 来源: https://blog.csdn.net/weixin_44003637/article/details/115012991