63 lines
1.4 KiB
C#
63 lines
1.4 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 开始监听指定的端口
|
|
/// </summary>
|
|
/// <param name="port">需要监听的端口号</param>
|
|
public void Connect(int port)
|
|
{
|
|
_endPoint = new IPEndPoint(IPAddress.Any, port);
|
|
_client = new UdpClient(_endPoint);
|
|
_isReceive = true;
|
|
|
|
_client.BeginReceive(ReceiveCallback, null);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 停止监听
|
|
/// </summary>
|
|
public void DisConnect()
|
|
{
|
|
_isReceive = false;
|
|
_client.Close();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 添加处理收到事件的回调
|
|
/// </summary>
|
|
/// <param name="handler"></param>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 处理收到数据的回调函数
|
|
/// </summary>
|
|
public delegate void ReceiveHandler(List<PoseLandmark> landmarks); |