Unity :Android局域网通信、UDP广播实现控制器开关(继电器)(01)

要解决的问题:

1.UDP广播:因为平板控制的不仅仅是继电器,还有其他电脑

2.继电器接收的是16进制指令,所以要把12个按钮1-12转换成16进制,要不然一个个的发送太麻烦,这里是指令的理解:指令理解,用于串口,继电器,控制板 - zqiang0803 - 博客园 (cnblogs.com)

下面直接上代码

客户端(发送命令的)

 

using System.Net.Sockets;
using System.Net;
using UnityEngine;
using System.Text;
using System;

public class UDPClient : MonoBehaviour
{
    private Socket socket;//目标socket
    private IPEndPoint ipEnd;//服务器
    private byte[] data;//发送的数据必须是字节
    public int udpPort = 8001;//服务器的端口
    public static UDPClient instance;//实例化SocketUDP,别的脚本里面 可以以 SocketUDP instance.形式访问

    public void Awake()
    {
        instance = this;

        //定义套接字类型,在主线程中定义
        //AddressFamily 寻址类型,InterNetwork代表IPV4。

        //SocketType 套接字类型
        //SocketType.Dgram表示使用数据报协议。

        //ProtocolType 协议类型
        //ProtocolType.Udp表示使用UDP协议,必须SocketType.Dgram,

        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        //该 Broadcast 字段等效于点四表示法中的 255.255.255.255。
        ipEnd = new IPEndPoint(IPAddress.Broadcast, udpPort);

        //设置socket,否则程序报错
        //SocketOptionLevel.Socket,默认
        // SocketOptionName.Broadcast 意思是广播,相当于255.255.255.255。
        //"1"表示,想IP段位中含1的IP中所有的IP发送信号
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
        Send("hello");
    }

    //发送英文(字符串)
    public void Send(string msg)
    {
        Debug.Log("发送消息:" + msg);
        data = Encoding.ASCII.GetBytes(msg);
        socket.SendTo(data, ipEnd);
    }

    //发送16进制的字符-多数用于控制器,继电器等设备
    public void SendHEX(string msg)
    {
        socket.SendTo(textWork16(msg), ipEnd);
    }
    private void OnApplicationQuit()
    {
        print("关闭");
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
    }
    // 字串符转换
    private byte[] textWork16(string strText)
    {
        strText = strText.Replace(" ", "");

        byte[] bText = new byte[strText.Length / 2];
        for (int i = 0; i < strText.Length / 2; i++)
        {
            bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
        }
        return bText;
    }
}

 

//调用方法

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClientTool : MonoBehaviour
{
    public GameObject allBtn;
    void Start()
    {
        for (int i = 0; i < allBtn.transform.childCount; i++)
        {
            GameObject obj = allBtn.transform.GetChild(i).gameObject;
            EventTriggerListener.Get(obj).onClick = onClick;
        }
    }
    void onClick(GameObject sender)
    {
        UDPClient.instance.Send(sender.name);
        //有时候同时发送,只能接收一个,可以协成   yield return new WaitForSeconds(0.01f);,间隔一下
        UDPClient.instance.SendHEX("5501130000000069");
    }
}

 测试:

 

posted on 2022-11-22 09:23  zqiang0803  阅读(627)  评论(0编辑  收藏  举报

导航