Skip to content

Commit

Permalink
migrate all relevant logic to csharp project instead of c++ project.
Browse files Browse the repository at this point in the history
  • Loading branch information
bobaoapae committed Nov 12, 2024
1 parent a490d18 commit 8c1ee36
Show file tree
Hide file tree
Showing 14 changed files with 224 additions and 257 deletions.
Binary file modified AneBuild/br.com.redesurftank.aneawesomeutils.ane
Binary file not shown.
Binary file modified AneBuild/windows-32/AneAwesomeUtilsWindows.dll
Binary file not shown.
Binary file modified AneBuild/windows-32/AwesomeAneUtils.dll
Binary file not shown.
11 changes: 11 additions & 0 deletions CSharpLibrary/AwesomeAneUtils/AwesomeAneUtils/DataArray.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Runtime.InteropServices;

namespace AwesomeAneUtils;

[StructLayout(LayoutKind.Sequential)]
public struct DataArray
{
public IntPtr DataPointer;
public int Size;
}
95 changes: 80 additions & 15 deletions CSharpLibrary/AwesomeAneUtils/AwesomeAneUtils/ExportFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace AwesomeAneUtils;
public static class ExportFunctions
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void UrlLoaderSuccessCallBackDelegate(IntPtr pointerGuid, IntPtr pointerArray, int length);
private delegate void UrlLoaderSuccessCallBackDelegate(IntPtr pointerGuid);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void UrlLoaderFailureCallBackDelegate(IntPtr pointerGuid, IntPtr pointerMessage);
Expand All @@ -30,7 +30,7 @@ public static class ExportFunctions
private delegate void WebSocketErrorCallBackDelegate(IntPtr pointerGuid, int closeCode, IntPtr pointerMessage);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void WebSocketDataCallBackDelegate(IntPtr pointerGuid, IntPtr pointerArray, int length);
private delegate void WebSocketDataCallBackDelegate(IntPtr pointerGuid);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void WriteLogCallBackDelegate(IntPtr pointerMessage);
Expand All @@ -43,12 +43,12 @@ public static class ExportFunctions
private static WebSocketDataCallBackDelegate _webSocketDataCallBackDelegate;
private static WriteLogCallBackDelegate _writeLogCallBackDelegate;

private static Action<string, byte[]> _urlLoaderSuccessWrapper;
private static Action<string> _urlLoaderSuccessWrapper;
private static Action<string, string> _urlLoaderFailureWrapper;
private static Action<string, string> _urlLoaderProgressWrapper;
private static Action<string> _webSocketConnectWrapper;
private static Action<string, int, string> _webSocketErrorWrapper;
private static Action<string, byte[]> _webSocketDataWrapper;
private static Action<string> _webSocketDataWrapper;
private static Action<string> _writeLogWrapper;

private static readonly ConcurrentDictionary<Guid, WebSocketClient> WebSocketClients = new();
Expand Down Expand Up @@ -89,16 +89,13 @@ public static int Initialize(
SafeFreeCoTaskMem(ptr1);
};

_urlLoaderSuccessWrapper = (guid, bytes) =>
_urlLoaderSuccessWrapper = (guid) =>
{
IntPtr ptr1 = Marshal.StringToCoTaskMemAnsi(guid);
IntPtr ptr2 = Marshal.AllocCoTaskMem(bytes.Length);
Marshal.Copy(bytes, 0, ptr2, bytes.Length);

_urlLoaderSuccessCallBackDelegate(ptr1, ptr2, bytes.Length);
_urlLoaderSuccessCallBackDelegate(ptr1);

SafeFreeCoTaskMem(ptr1);
SafeFreeCoTaskMem(ptr2);
};

_urlLoaderFailureWrapper = (guid, error) =>
Expand Down Expand Up @@ -143,16 +140,13 @@ public static int Initialize(
SafeFreeCoTaskMem(ptr2);
};

_webSocketDataWrapper = (guid, data) =>
_webSocketDataWrapper = (guid) =>
{
IntPtr ptr1 = Marshal.StringToCoTaskMemAnsi(guid);
IntPtr ptr2 = Marshal.AllocCoTaskMem(data.Length);
Marshal.Copy(data, 0, ptr2, data.Length);

_webSocketDataCallBackDelegate(ptr1, ptr2, data.Length);
_webSocketDataCallBackDelegate(ptr1);

SafeFreeCoTaskMem(ptr1);
SafeFreeCoTaskMem(ptr2);
};
}
catch
Expand Down Expand Up @@ -191,7 +185,7 @@ public static IntPtr CreateWebSocket()

var webSocketClient = new WebSocketClient(
() => { _webSocketConnectWrapper(guidString); },
data => { _webSocketDataWrapper(guidString, data.Array); },
() => { _webSocketDataWrapper(guidString); },
(errorCode, error) =>
{
using (lockError.EnterScope())
Expand Down Expand Up @@ -299,6 +293,44 @@ public static int CloseWebSocket(IntPtr guidPointer, int closeCode)
}
}

[UnmanagedCallersOnly(EntryPoint = "csharpLibrary_awesomeUtils_getWebSocketMessage", CallConvs = [typeof(CallConvCdecl)])]
public static DataArray GetWebSocketMessage(IntPtr guidPointer)
{
var result = new DataArray();

try
{
var guidString = Marshal.PtrToStringAnsi(guidPointer);

if (!Guid.TryParse(guidString, out var guid))
{
return result;
}

if (!WebSocketClients.TryGetValue(guid, out var client))
{
return result;
}

if (!client.TryGetNextMessage(out var message))
{
return result;
}

result.Size = message.Length;

result.DataPointer = Marshal.AllocHGlobal(result.Size);
Marshal.Copy(message, 0, result.DataPointer, result.Size);

return result;
}
catch (Exception e)
{
LogAll(e, _writeLogWrapper);
return result;
}
}

[UnmanagedCallersOnly(EntryPoint = "csharpLibrary_awesomeUtils_addStaticHost", CallConvs = [typeof(CallConvCdecl)])]
public static void AddStaticHost(IntPtr hostPtr, IntPtr ipPtr)
{
Expand Down Expand Up @@ -352,6 +384,39 @@ public static IntPtr LoadUrl(IntPtr urlPtr, IntPtr methodPtr, IntPtr variablesPt
}
}

[UnmanagedCallersOnly(EntryPoint = "csharpLibrary_awesomeUtils_getLoaderResult", CallConvs = [typeof(CallConvCdecl)])]
public static DataArray GetLoaderResult(IntPtr guidPointer)
{
var result = new DataArray();

try
{
var guidString = Marshal.PtrToStringAnsi(guidPointer);

if (!Guid.TryParse(guidString, out var guid))
{
return result;
}

if (!LoaderManager.Instance.TryGetResult(guid, out var data))
{
return result;
}

result.Size = data.Length;

result.DataPointer = Marshal.AllocHGlobal(result.Size);
Marshal.Copy(data, 0, result.DataPointer, result.Size);

return result;
}
catch (Exception e)
{
LogAll(e, _writeLogWrapper);
return result;
}
}

[UnmanagedCallersOnly(EntryPoint = "csharpLibrary_awesomeUtils_deviceUniqueId", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr get_deviceUniqueId()
{
Expand Down
33 changes: 28 additions & 5 deletions CSharpLibrary/AwesomeAneUtils/AwesomeAneUtils/LoaderManager.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

Expand All @@ -16,20 +18,22 @@ public class LoaderManager

public bool Initialized { get; private set; }

private Action<string, byte[]> _success;
private Action<string> _success;
private Action<string, string> _error;
private Action<string, string> _progress;
private Action<string> _writeLog;
private HttpClient _client;
private ConcurrentDictionary<Guid, byte[]> _results;

public void Initialize(Action<string, byte[]> success, Action<string, string> error, Action<string, string> progress, Action<string> writeLog)
public void Initialize(Action<string> success, Action<string, string> error, Action<string, string> progress, Action<string> writeLog)
{
Initialized = true;
_success = success;
_error = error;
_progress = progress;
_writeLog = writeLog;
_client = HappyEyeballsHttp.CreateHttpClient(true, _writeLog);
_results = new ConcurrentDictionary<Guid, byte[]>();
}

public string StartLoad(string url, string method, Dictionary<string, string> variables, Dictionary<string, string> headers)
Expand Down Expand Up @@ -92,7 +96,7 @@ public string StartLoad(string url, string method, Dictionary<string, string> va
using var memoryStream = new MemoryStream();

int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
Expand All @@ -105,11 +109,25 @@ public string StartLoad(string url, string method, Dictionary<string, string> va
}

var result = memoryStream.ToArray();
if (!_results.TryAdd(randomId, result))
{
try
{
_error(randomId.ToString(), $"Failed to add result for {randomId}");
}
catch (Exception)
{
// ignored
}

return;
}

_ = Task.Run(() =>
{
try
{
_success(randomId.ToString(), result);
_success(randomId.ToString());
}
catch (Exception e)
{
Expand Down Expand Up @@ -147,14 +165,19 @@ public string StartLoad(string url, string method, Dictionary<string, string> va
return randomId.ToString();
}

public bool TryGetResult(Guid guid, out byte[] result)
{
return _results.TryGetValue(guid, out result);
}

private void LogAll(Exception exception)
{
if (exception == null)
return;

try
{
var logBuilder = new System.Text.StringBuilder();
var logBuilder = new StringBuilder();

// Log the main exception
logBuilder.AppendLine($"Exception: {exception.Message}");
Expand Down
34 changes: 23 additions & 11 deletions CSharpLibrary/AwesomeAneUtils/AwesomeAneUtils/WebSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,9 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using DnsClient;

namespace AwesomeAneUtils;

Expand All @@ -23,22 +17,23 @@ public class WebSocketClient : IDisposable

// Callbacks
private readonly Action _onConnect;
private readonly Action<ArraySegment<byte>> _onReceived;
private readonly Action _onReceived;
private readonly Action<int, string> _onIoError;
private readonly Action<string> _onLog;

private ClientWebSocket _activeWebSocket;
private bool _disposed;
private bool _isDisconnectCalled;
private ConcurrentQueue<IMemoryOwner<byte>> _receiveQueue = new();

public WebSocketClient(Action onConnect, Action<ArraySegment<byte>> onReceived, Action<int, string> onIoError, Action<string> onLog)
public WebSocketClient(Action onConnect, Action onReceived, Action<int, string> onIoError, Action<string> onLog)
{
_onConnect = onConnect;
_onReceived = onReceived;
_onIoError = onIoError;
_onLog = onLog;
}

public void Connect(string uri)
{
_ = Task.Run(async () => await ConnectAsync(uri));
Expand Down Expand Up @@ -303,7 +298,10 @@ private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
}
} while (!result.EndOfMessage); // Keep receiving until the end of the message

_onReceived?.Invoke(new ArraySegment<byte>(buffer, 0, totalBytesReceived));
var memory = MemoryPool<byte>.Shared.Rent(totalBytesReceived);
buffer.AsSpan(..totalBytesReceived).CopyTo(memory.Memory.Span);
_receiveQueue.Enqueue(memory);
_onReceived?.Invoke();
_onLog?.Invoke("Message received.");
}
}
Expand All @@ -323,9 +321,23 @@ public void Disconnect(int closeReason)
_ = Task.Run(async () => await DisconnectAsync(closeReason));
}

public bool TryGetNextMessage(out byte[] data)
{
data = [];
if (_isDisconnectCalled)
return false;

if (!_receiveQueue.TryDequeue(out var memory))
return false;

data = memory.Memory.ToArray();
memory.Dispose();
return true;
}

private async Task DisconnectAsync(int closeReason, string reason = "Closing connection gracefully.")
{
if(!_isDisconnectCalled)
if (!_isDisconnectCalled)
_onIoError?.Invoke(closeReason, reason);
if (_activeWebSocket is { State: WebSocketState.Open or WebSocketState.CloseReceived })
{
Expand Down
3 changes: 1 addition & 2 deletions WindowsNative/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ add_library(AneAwesomeUtilsWindows SHARED
src/AneAwesomeUtilsCsharp.cpp
src/AneAwesomeUtilsCsharp.h
src/AneAwesomeUtilsSupport.cpp
src/WebSocketClient.cpp
src/WebSocketClient.h
src/DataArray.h
)

target_link_libraries(AneAwesomeUtilsWindows PRIVATE ${LIBRARY_PATH}/FlashRuntimeExtensions.lib)
Expand Down
Loading

0 comments on commit 8c1ee36

Please sign in to comment.