| | 1 | | using System; |
| | 2 | | using System.Runtime.InteropServices; |
| | 3 | | using AOT; |
| | 4 | | using rpc_csharp.transport; |
| | 5 | |
|
| | 6 | | namespace RPC.Transports |
| | 7 | | { |
| | 8 | | public class WebGLTransport : ITransport |
| | 9 | | { |
| | 10 | | public event Action OnCloseEvent; |
| | 11 | |
|
| | 12 | | public event Action<string> OnErrorEvent; |
| | 13 | |
|
| | 14 | | public event Action<byte[]> OnMessageEvent; |
| | 15 | |
|
| | 16 | | public event Action OnConnectEvent; |
| | 17 | |
|
| 0 | 18 | | public WebGLTransport() |
| | 19 | | { |
| | 20 | | #if UNITY_WEBGL && !UNITY_EDITOR |
| | 21 | | SetCallback_BinaryMessage(BinaryMessage); |
| | 22 | | #endif |
| 0 | 23 | | OnWebGLMessage += OnWebgGLMessageReceived; |
| 0 | 24 | | } |
| | 25 | |
|
| | 26 | | public void SendMessage(byte[] data) |
| | 27 | | { |
| 0 | 28 | | BinaryMessageFromEngine(data, data.Length); |
| 0 | 29 | | } |
| | 30 | |
|
| | 31 | | public void Close() |
| | 32 | | { |
| 0 | 33 | | OnWebGLMessage -= OnWebgGLMessageReceived; |
| 0 | 34 | | } |
| | 35 | |
|
| | 36 | | private void OnWebgGLMessageReceived(byte[] data) |
| | 37 | | { |
| 0 | 38 | | OnMessageEvent?.Invoke(data); |
| 0 | 39 | | } |
| | 40 | |
|
| | 41 | | delegate void JS_Delegate_VII(int a, int b); |
| | 42 | |
|
| | 43 | | #if UNITY_WEBGL && !UNITY_EDITOR |
| | 44 | | [DllImport("__Internal")] public static extern void BinaryMessageFromEngine(byte[] bytes, int size); |
| | 45 | | #else |
| 0 | 46 | | private static void BinaryMessageFromEngine(byte[] bytes, int size) { } |
| | 47 | | #endif |
| | 48 | |
|
| | 49 | | private static event Action<byte[]> OnWebGLMessage; |
| | 50 | |
|
| | 51 | | [DllImport("__Internal")] |
| | 52 | | private static extern void SetCallback_BinaryMessage(JS_Delegate_VII callback); |
| | 53 | |
|
| | 54 | | [MonoPInvokeCallback(typeof(JS_Delegate_VII))] |
| | 55 | | internal static void BinaryMessage(int intPtr, int length) |
| | 56 | | { |
| 0 | 57 | | byte[] data = new byte[length]; |
| 0 | 58 | | Marshal.Copy(new IntPtr(intPtr), data, 0, length); |
| 0 | 59 | | OnWebGLMessage?.Invoke(data); |
| 0 | 60 | | } |
| | 61 | | } |
| | 62 | | } |