1
0

UdpConnection.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. private Action<EcgData> onEcgData;
  17. public UdpConnection(String ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData)
  18. {
  19. this.onAccData = onAccData;
  20. this.onEcgData = onEcgData;
  21. client = new UdpClient(new IPEndPoint(IPAddress.Parse(ipAddress), port));
  22. }
  23. public void Listen() => Task.Run(async () =>
  24. {
  25. listening = true;
  26. while (listening)
  27. {
  28. var result = await client.ReceiveAsync();
  29. String receivedStr = Encoding.UTF8.GetString(result.Buffer);
  30. var data = receivedStr.Split(':');
  31. if (data.Length == 2)
  32. {
  33. var name = data[0];
  34. if (name.Equals("ACC"))
  35. {
  36. onAccData(AccData.FromString(data[1]));
  37. }else if (name.Equals("ECG"))
  38. {
  39. onEcgData(EcgData.FromString(data[1]));
  40. }else if (name.Equals("HR"))
  41. {
  42. //TODO
  43. }
  44. }
  45. Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
  46. }
  47. });
  48. public void StopListening()
  49. {
  50. listening = false;
  51. }
  52. }