Unity UDP通信代码(按钮控制发送随机数组)

using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Udp : MonoBehaviour
{
    private Socket socket;
    private IPEndPoint remoteEndPoint;
    public InputField thisField;
    float lastRecvMessage;
    // 初始化Socket
    void Start()
    {
        // 创建套接字
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        // 绑定本地端点
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.43.68"), 33033);
        socket.Bind(localEndPoint);

        // 设置远程端点
        remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.43.68"), 33032);

        // 启动接收协程
        StartCoroutine(ReceiveData());
        //SendMessage();
    }

    // 协程用于持续接收数据
    private IEnumerator ReceiveData()
    {
        byte[] recvBuffer = new byte[512];
        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

        while (true)
        {
            if (socket.Poll(1000, SelectMode.SelectRead))
            {
                int recvLen = socket.ReceiveFrom(recvBuffer, ref remoteEP);
                float recvMessage = (float)BitConverter.ToDouble(recvBuffer, 0);
                //float recvMessage = BitConverter.ToSingle(recvBuffer, 0);
                //string recvMessage = Encoding.UTF8.GetString(recvBuffer, 0, recvLen);
                //bug.Log((remoteEP as IPEndPoint).Address.ToString() + " 发来了: " + recvMessage);

                if (lastRecvMessage != 0|| recvMessage != lastRecvMessage)
                {
                    Debug.Log((remoteEP as IPEndPoint).Address.ToString() + " 发来了: " + recvMessage);
                    lastRecvMessage = recvMessage; // 更新上一次接收到的数据
                }
            }

            yield return null; // 等待下一帧继续接收数据
        }
    }
    public void SendMessage()
    {

        // 定义四个浮点数
        //double a = 0.9502f;
        //double b = 0.2414f;
        //double c = 0.3892f;
        //double d = 0.1223f;

        // 使用 System.Random 生成四个 [0, 1] 范围内的随机数
        System.Random rand = new System.Random();
        double a = rand.NextDouble();
        double b = rand.NextDouble();
        double c = rand.NextDouble();
        double d = rand.NextDouble();
        // 将每个浮点数转换为字节数组
        byte[] bytesA = BitConverter.GetBytes(a);
        byte[] bytesB = BitConverter.GetBytes(b);
        byte[] bytesC = BitConverter.GetBytes(c);
        byte[] bytesD = BitConverter.GetBytes(d);
       
        // 创建一个字节数组来存储所有浮点数的字节
        byte[] sendData = new byte[bytesA.Length + bytesB.Length + bytesC.Length + bytesD.Length];

        // 复制字节数组到 sendData 中
        Buffer.BlockCopy(bytesA, 0, sendData, 0, bytesA.Length);
        Buffer.BlockCopy(bytesB, 0, sendData, bytesA.Length, bytesB.Length);
        Buffer.BlockCopy(bytesC, 0, sendData, bytesA.Length + bytesB.Length, bytesC.Length);
        Buffer.BlockCopy(bytesD, 0, sendData, bytesA.Length + bytesB.Length + bytesC.Length, bytesD.Length);

        // 通过 UDP 发送数据
        socket.SendTo(sendData, remoteEndPoint);
       
        Debug.Log("消息已发送: " + a + ", " + b + ", " + c + ", " + d);
    }
    // 发送数据
    //public void SendMessage()
    //{
    //    //byte[] sendData = Encoding.UTF8.GetBytes(message);
    //    //socket.SendTo(sendData, remoteEndPoint);
    //    //Debug.Log("消息已发送: " + message);
    //    //double parsedValue = double.Parse(message);
    //    double parsedValue = (0.1,0.2,0.3,0.4);
    //    byte[] sendData = BitConverter.GetBytes(parsedValue); // 将 double 转换为 byte 数组
    //    socket.SendTo(sendData, remoteEndPoint);
    //    //Debug.Log("消息已发送: " + message);

    //}
    public void tosendstring()
    {
        SendMessage();
    }
    // 清理资源
    private void OnApplicationQuit()
    {
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值