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_UDPGet : MonoBehaviour
{
public string LocalIP;//本地IP
public int LocalPORT;//本地端口
public float GetOutTime;//心跳超时时间(秒)
public bool TimeOut = false;//超时标记
public float ClockTimeDelay;//心跳检测间隔(秒)
private Queue GetQueue;//用于接收的数据队列
private UdpClient udpGet;//udp
private IPEndPoint GetServerPoint;//监听地址
private MyThread GetThread;//数据队列收发线程
private MyThread ClockThread;//心跳线程
private DateTime LateTime;//心跳计时
public Queue GetDataQueue()//获取接收的消息队列
{
return GetQueue;
}
private void Awake()
{
GetQueue = new Queue();
LateTime = DateTime.Now;//刷新心跳时间
IPAddress ServerIp = Dns.GetHostEntry(Dns.GetHostName()).AddressList[2];
LocalIP = ServerIp.ToString(); //获取本地IP
udpGet = new UdpClient(new IPEndPoint(IPAddress.Parse(LocalIP), LocalPORT)); //绑定IP和端口
GetServerPoint = new IPEndPoint(IPAddress.Any, 0);//监听接收的所有消息
//=[线程启动]======
GetThread = new MyThread(DataQueueProcessor);
ClockThread = new MyThread(ClockCheck);
GetThread.Start();
ClockThread.Start();
}
private void DataQueueProcessor(MyThread Bit)//数据队列处理器
{
while (Bit.isStart)
{
try
{
byte[] data = udpGet.Receive(ref GetServerPoint);//阻塞式接受数据
GetQueue.Enqueue(data);//添加到队列
LateTime = DateTime.Now;//刷新心跳时间
}
catch
{
}
}
}
private void ClockCheck(MyThread Bit)//心跳检测线程
{
while (Bit.isStart)
{
TimeOut = TriggerMarker.Clock(ref LateTime, ClockTimeDelay);//心跳超时检测
Thread.Sleep((int)GetOutTime * 1000);//处理延时
}
}
void OnApplicationQuit()//释放资源
{
GetThread.End();
ClockThread.End();
udpGet.Close();
}
void OnDestroy()//释放资源
{
GetThread.End();
ClockThread.End();
udpGet.Close();
}
}
}