using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using MyTool.Static;
using System;
using System.Threading.Tasks;
/*
* 作者:闪电Y黑客
*
* 日期:2019.5.5
*
* 功能:用于UDP通讯的发送端
*
* 注:知识量不足,暂时做为组件
*
*/
namespace MyTool.Component
{
/// <summary>
/// UDP发送端
/// </summary>
public class MyComponent_UDPSet : MonoBehaviour
{
public string SetIP;//目标IP
public int SetPORT;//目标端口
public float SetTimeDelay;//发送间隔(秒)
public bool StartClock = false;//是否启动心跳
public float ClockTimeDelay;//心跳发送间隔(秒)
private Queue SetQueue;//用于发送的数据队列
private UdpClient udpSet;//udp
private IPEndPoint SetServerPoint;//客户端地址
private MyThread SetThread;//客户端接收线程
private DateTime LateTime;//用于心跳计时
public void SetDataQueue(byte[] data)//添加发送数据队列
{
SetQueue.Enqueue(data);
}
private void Awake()
{
SetQueue = new Queue();
LateTime = DateTime.Now;//刷新心跳时间
udpSet = new UdpClient();
SetServerPoint = new IPEndPoint(IPAddress.Parse(SetIP), SetPORT);//发送服务器端口IP
//=[线程启动]======
SetThread = new MyThread(DataQueueProcessor);
SetThread.Start();
}
private void DataQueueProcessor(MyThread Bit)//数据队列处理器
{
while (Bit.isStart)
{
if (TriggerMarker.Clock(ref LateTime, ClockTimeDelay) && StartClock)//心跳时间判断
{
SetQueue.Enqueue(new byte[] { 1 });//心跳消息暂时为Byte 1
LateTime = DateTime.Now;//刷新心跳时间
}
if (SetQueue.Count > 0)//发送数据
{
byte[] data = (byte[])SetQueue.Dequeue();
udpSet.Send(data, data.Length, SetServerPoint);//针对发送数据
LateTime = DateTime.Now;//刷新心跳时间
}
Thread.Sleep((int)SetTimeDelay * 1000);//处理延时
}
}
void OnApplicationQuit()//释放资源
{
SetThread.End();
udpSet.Close();
}
void OnDestroy()//释放资源
{
SetThread.End();
udpSet.Close();
}
}
}