(tools, client, server) feat: Remove gRPC support, add TCP back and reorganized project
This commit is contained in:
70
Client/Assets/Scripts/Network/UnityTcpClient.cs
Normal file
70
Client/Assets/Scripts/Network/UnityTcpClient.cs
Normal file
@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using Utils;
|
||||
|
||||
namespace Network
|
||||
{
|
||||
public class UnityTcpClient : Singleton<UnityTcpClient>, IDisposable
|
||||
{
|
||||
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[1024];
|
||||
await stream.ReadAsync(buffer);
|
||||
return 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;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user