Unity 简单UDP客户端

//两个UDP实例分别负责收发数据

using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class UDPCommunication : MonoBehaviour
{
    public Text Text;
    private UdpClient senderClient;
    private UdpClient receiverClient;
    private CancellationTokenSource cts = new CancellationTokenSource();

    // 服务器的IP地址和端口
    private string serverIP = "127.0.0.1";
    private int sendPort = 30002;  // 发送数据到服务器的端口
    private int receivePort = 30003; // 从服务器接收数据的端口
    private IPEndPoint sendEndPoint;

    void Start()
    {

        sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
        senderClient = new UdpClient();
        senderClient.Connect(sendEndPoint);

        receiverClient = new UdpClient(receivePort);
        ReceiveMessages(cts.Token);
    }

    public void SendData(string message)
    {
        try
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            senderClient.Send(data, data.Length);
        }
        catch (Exception err)
        {
            Debug.Log(err.ToString());
        }
    }

    private async Task ReceiveMessages(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            try
            {
                UdpReceiveResult result = await receiverClient.ReceiveAsync();
                if (token.IsCancellationRequested)
                    break;

                string receivedData = Encoding.UTF8.GetString(result.Buffer);
                Text.text = receivedData;
            }
            catch (Exception err)
            {
                Debug.Log(err.ToString());
                if (token.IsCancellationRequested)
                    break; // 如果是因为取消引发的异常,则退出循环
                await Task.Delay(1000); // 等待一秒再继续
            }
        }
    }
    //仅使用OnDestroy释放资源就好了
    void OnDestroy()
    {
        CloseConnections();
    }

    private void CloseConnections()
    {
        if (cts != null)
        {
            cts.Cancel(); // 发送取消信号
            if (senderClient != null)
            {
                senderClient.Close();
                senderClient = null;
            }
            if (receiverClient != null)
            {
                receiverClient.Close();
                receiverClient = null;
            }
            cts.Dispose(); // 清理 CancellationTokenSource 资源
        }
        cts = null;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值