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]);
}
}
版权声明:本文为qq_38834505原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。