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 두 스크립트는 플랫폼간에 사용할 수있는 두 프로그램에 해당합니다.