SocketProxy.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using UnityEngine;
  7. namespace LightReflectiveMirror
  8. {
  9. // This class handles the proxying from punched socket to transport.
  10. public class SocketProxy
  11. {
  12. public DateTime lastInteractionTime;
  13. public Action<IPEndPoint, byte[]> dataReceived;
  14. UdpClient _udpClient;
  15. IPEndPoint _recvEndpoint = new IPEndPoint(IPAddress.Any, 0);
  16. IPEndPoint _remoteEndpoint;
  17. bool _clientInitialRecv = false;
  18. public SocketProxy(int port, IPEndPoint remoteEndpoint)
  19. {
  20. _udpClient = new UdpClient();
  21. _udpClient.Connect(new IPEndPoint(IPAddress.Loopback, port));
  22. _udpClient.BeginReceive(new AsyncCallback(RecvData), _udpClient);
  23. lastInteractionTime = DateTime.Now;
  24. // Clone it so when main socket recvies new data, it wont switcheroo on us.
  25. _remoteEndpoint = new IPEndPoint(remoteEndpoint.Address, remoteEndpoint.Port);
  26. }
  27. public SocketProxy(int port)
  28. {
  29. _udpClient = new UdpClient(port);
  30. _udpClient.BeginReceive(new AsyncCallback(RecvData), _udpClient);
  31. lastInteractionTime = DateTime.Now;
  32. }
  33. public void RelayData(byte[] data, int length)
  34. {
  35. _udpClient.Send(data, length);
  36. lastInteractionTime = DateTime.Now;
  37. }
  38. public void ClientRelayData(byte[] data, int length)
  39. {
  40. if (_clientInitialRecv)
  41. {
  42. _udpClient.Send(data, length, _recvEndpoint);
  43. lastInteractionTime = DateTime.Now;
  44. }
  45. }
  46. public void Dispose()
  47. {
  48. _udpClient.Dispose();
  49. }
  50. void RecvData(IAsyncResult result)
  51. {
  52. byte[] data = _udpClient.EndReceive(result, ref _recvEndpoint);
  53. _udpClient.BeginReceive(new AsyncCallback(RecvData), _udpClient);
  54. _clientInitialRecv = true;
  55. lastInteractionTime = DateTime.Now;
  56. dataReceived?.Invoke(_remoteEndpoint, data);
  57. }
  58. }
  59. }