PolarClient.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. public class PolarClient
  8. {
  9. private static bool running = false;
  10. private static UdpClient client;
  11. //TODO: onData callback
  12. public static void Start(string ipAddress, int port)
  13. {
  14. var endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
  15. client = new UdpClient();
  16. try
  17. {
  18. Debug.Log("PolarClient: Connecting to server");
  19. client.Connect(endPoint);
  20. running = true;
  21. Debug.Log($"PolarClient: Connected to server: {client.Client.Connected}");
  22. var d = Encoding.UTF8.GetBytes("Blabla");
  23. client.Send(d, d.Length);
  24. while (running)
  25. {
  26. var data = client.Receive(ref endPoint);
  27. HandleData(data);
  28. }
  29. /*await Task.Run(()
  30. =>
  31. {
  32. })*;*/
  33. }
  34. catch (Exception e)
  35. {
  36. Debug.Log($"PolarClient Error: {e}");
  37. }
  38. }
  39. private static void Stop()
  40. {
  41. running = false;
  42. client.Dispose();
  43. }
  44. private static void HandleData(byte[] data)
  45. {
  46. Debug.Log($"PolarClient Data: {Encoding.UTF8.GetString(data)}");
  47. }
  48. }