微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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两个脚本对应两个程序,可以跨平台使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐