2
0

UdpConnection.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using UnityEngine;
  9. public class UdpConnection
  10. {
  11. //public int port = 9090;
  12. //public String ipAddress = "192.168.1.7";
  13. private UdpClient client;
  14. private bool listening = false;
  15. private Action<AccData> onAccData;
  16. public UdpConnection(String ipAddress, int port, Action<AccData> onAccData)
  17. {
  18. this.onAccData = onAccData;
  19. client = new UdpClient(new IPEndPoint(IPAddress.Parse(ipAddress), port));
  20. }
  21. public void Listen() => Task.Run(async () =>
  22. {
  23. listening = true;
  24. while (listening)
  25. {
  26. var result = await client.ReceiveAsync();
  27. String receivedStr = Encoding.UTF8.GetString(result.Buffer);
  28. var data = receivedStr.Split(':');
  29. if (data.Length == 2)
  30. {
  31. var name = data[0];
  32. if (name.Equals("ACC"))
  33. {
  34. onAccData(AccData.fromString(data[1]));
  35. }else if (name.Equals("ECG"))
  36. {
  37. //TODO
  38. }else if (name.Equals("HR"))
  39. {
  40. //TODO
  41. }
  42. }
  43. Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
  44. }
  45. });
  46. public void StopListening()
  47. {
  48. listening = false;
  49. }
  50. }