using System; using System.Net.Sockets; using System.Threading.Tasks; using UnityEngine; using Utils; namespace Network { public class UnityUdpClient : Singleton, IDisposable { private UdpClient _client; private bool _disposed; public UnityUdpClient() { try { _client = new UdpClient(); _client.Connect("127.0.0.1", 12345); Application.quitting += Dispose; } catch (Exception ex) { Debug.LogException(ex); return; } } public async Task SendAndReceiveData(byte[] data) { try { await _client.SendAsync(data, data.Length); var result = await _client.ReceiveAsync(); return result.Buffer; } catch (Exception ex) { Debug.LogException(ex); return new byte[0]; } } public void Dispose() { if (_disposed) return; try { _client.Close(); _client.Dispose(); } catch (Exception ex) { Debug.LogException(ex); return; } finally { _client = null; } _disposed = true; } } }