using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Models;
public class UdpListener
{
private UdpClient _client;
private IPEndPoint _endPoint;
private bool _isReceive;
private ReceiveHandler _handlers;
///
/// 开始监听指定的端口
///
/// 需要监听的端口号
public void Connect(int port)
{
_endPoint = new IPEndPoint(IPAddress.Any, port);
_client = new UdpClient(_endPoint);
_isReceive = true;
_client.BeginReceive(ReceiveCallback, null);
}
///
/// 停止监听
///
public void DisConnect()
{
_isReceive = false;
_client.Close();
}
///
/// 添加处理收到事件的回调
///
///
public void AddHandler(ReceiveHandler handler)
{
_handlers += handler;
}
private void ReceiveCallback(IAsyncResult result)
{
if (_isReceive)
{
var bytes = _client.EndReceive(result, ref _endPoint);
var landmarks = PoseLandmark.ArrayOf(bytes);
_handlers(landmarks);
_client.BeginReceive(ReceiveCallback, null);
}
}
}
///
/// 处理收到数据的回调函数
///
public delegate void ReceiveHandler(List landmarks);