接收Udp数据

附赠3D立方体旋转一小时
This commit is contained in:
jackfiled 2023-02-10 16:17:18 +08:00
parent d288e05988
commit d38b44b8ac
4 changed files with 115 additions and 0 deletions

38
Assets/CubeBehaviour.cs Normal file
View File

@ -0,0 +1,38 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Models;
using UnityEngine;
public class CubeBehaviour : MonoBehaviour
{
public Vector3 rotateAmount = new Vector3(0, 1, 0);
private readonly UdpListener _listener = new UdpListener();
// Start is called before the first frame update
private void Start()
{
_listener.AddHandler(LogLandmarks);
_listener.Connect(5000);
}
// Update is called once per frame
private void Update()
{
transform.Rotate(rotateAmount);
}
private void OnDisable()
{
_listener.DisConnect();
}
private static void LogLandmarks(List<PoseLandmark> landmarks)
{
foreach (var landmark in landmarks)
{
Debug.Log(landmark.ToString());
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 11e8a976fe328b1c3bdf9f44ef9f6fa1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

63
Assets/UdpListener.cs Normal file
View File

@ -0,0 +1,63 @@
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);

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0eea15b46d04475e8de7277ef64e39e0
timeCreated: 1676014658