unity udp通信 发送命令

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;

public class Udpsend : MonoBehaviour
{
    public Button[] btns;
    private Socket socketclient;
    private IPEndPoint iep;
    private byte[] bytesendingarray;
    string[] readtxt;
    // Use this for initialization
    void Start()
    {

        string filepath = Application.dataPath + "/StreamingAssets/配置文件.txt";
        readtxt = File.ReadAllLines(filepath);

        iep = new IPEndPoint(IPAddress.Parse(readtxt[0]), 9000);

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

        
        for (int i = 1; i < readtxt.Length; i++)//因为我的txt里面的内容是“控制第一路开 FE 05 00 00 FF 00 98 35 ”所以要去掉前7个字符
        {
            readtxt[i] = readtxt[i].Remove(0, 7);

        }

        for (int i = 0; i < btns.Length; i++)
        {
            int index = i + 1;
            btns[i].onClick.AddListener(() =>
            {

                OnSendRequest(readtxt[13]); //全关
                print("发送成功" + readtxt[13]);
                StartCoroutine(SendTime(readtxt[index]));
                print("发送成功" + readtxt[index]);
            });

        }
        OnSendRequest(readtxt[14]); //全开

    }

    // Update is called once per framepdate()
    
    IEnumerator SendTime(string str)
    {//等待0.5s后发送下一条指令
        yield return new WaitForSeconds(0.5f);
        OnSendRequest(str);
    }
    public void OnSendRequest(string str)
    {//发送

        socketclient.SendTo(StrtoHexByte(str), iep);

    }
    private static byte[] StrtoHexByte(string hexstring)
    {//字符串转16进制
        hexstring = hexstring.Replace(" ", "");
        if ((hexstring.Length % 2) != 0)
        {
            hexstring += " ";
        }
        byte[] returnbytes = new byte[hexstring.Length / 2];
        for (int i = 0; i < returnbytes.Length; i++)
        {
            returnbytes[i] = Convert.ToByte(hexstring.Substring(i * 2, 2), 16);
        }
        return returnbytes;

    }

    /// <summary>
    /// Callback sent to all game objects before the application is quit.
    /// </summary>
    void OnApplicationQuit()
    {
        socketclient.Close();
    }
    public void Qk(){//全开指令
        OnSendRequest(readtxt[14]);
    }
	
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值