72 lines
1.6 KiB
C#
72 lines
1.6 KiB
C#
using System;
|
|
using System.Net.Sockets;
|
|
using System.Threading.Tasks;
|
|
using UnityEngine;
|
|
using Utils;
|
|
|
|
namespace Network
|
|
{
|
|
public class UnityTcpClient : Singleton<UnityTcpClient>, IDisposable
|
|
{
|
|
private const int TcpMaxPayloadSize = 1460;
|
|
|
|
private TcpClient _client;
|
|
private bool _disposed;
|
|
|
|
public UnityTcpClient()
|
|
{
|
|
try
|
|
{
|
|
_client = new TcpClient();
|
|
_client.Connect("127.0.0.1", 12345);
|
|
Application.quitting += Dispose;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogException(ex);
|
|
return;
|
|
}
|
|
}
|
|
|
|
public async Task<byte[]> SendAndReceiveData(byte[] data)
|
|
{
|
|
try
|
|
{
|
|
await using var stream = _client.GetStream();
|
|
|
|
await stream.WriteAsync(data, 0, data.Length);
|
|
|
|
var buffer = new byte[TcpMaxPayloadSize];
|
|
var len = await stream.ReadAsync(buffer);
|
|
return buffer[..len];
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
} |