Skip to content

Commit

Permalink
Merge branch 'master' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Sep 3, 2020
2 parents ec3b136 + 30c9b7d commit 90326e4
Showing 1 changed file with 76 additions and 2 deletions.
78 changes: 76 additions & 2 deletions Assets/Plugins/WebSocket/WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,75 @@

using AOT;
using System.Runtime.InteropServices;
using UnityEngine;
using System.Collections;

public class MainThreadUtil : MonoBehaviour
{
public static MainThreadUtil Instance { get; private set; }
public static SynchronizationContext synchronizationContext { get; private set; }

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Setup()
{
Instance = new GameObject("MainThreadUtil")
.AddComponent<MainThreadUtil>();
synchronizationContext = SynchronizationContext.Current;
}

public static void Run(IEnumerator waitForUpdate)
{
synchronizationContext.Post(_ => Instance.StartCoroutine(
waitForUpdate), null);
}

void Awake()
{
gameObject.hideFlags = HideFlags.HideAndDontSave;
DontDestroyOnLoad(gameObject);
}
}

public class WaitForUpdate : CustomYieldInstruction
{
public override bool keepWaiting
{
get { return false; }
}

public MainThreadAwaiter GetAwaiter()
{
var awaiter = new MainThreadAwaiter();
MainThreadUtil.Run(CoroutineWrapper(this, awaiter));
return awaiter;
}

public class MainThreadAwaiter : INotifyCompletion
{
Action continuation;

public bool IsCompleted { get; set; }

public void GetResult() { }

public void Complete()
{
IsCompleted = true;
continuation?.Invoke();
}

void INotifyCompletion.OnCompleted(Action continuation)
{
this.continuation = continuation;
}
}

public static IEnumerator CoroutineWrapper(IEnumerator theWorker, MainThreadAwaiter awaiter)
{
yield return theWorker;
awaiter.Complete();
}
}

namespace NativeWebSocket
{
Expand Down Expand Up @@ -490,6 +559,7 @@ public void DispatchMessageQueue()

public async Task Receive()
{
WebSocketCloseCode closeCode = WebSocketCloseCode.Abnormal;
await new WaitForBackgroundThread();

ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[8192]);
Expand Down Expand Up @@ -531,7 +601,7 @@ public async Task Receive()
else if (result.MessageType == WebSocketMessageType.Close)
{
await Close();
OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus));
closeCode = WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus);
break;
}
}
Expand All @@ -540,7 +610,11 @@ public async Task Receive()
catch (Exception)
{
m_TokenSource.Cancel();
OnClose?.Invoke(WebSocketCloseCode.Abnormal);
}
finally
{
await new WaitForUpdate();
OnClose?.Invoke(closeCode);
}
}

Expand Down

0 comments on commit 90326e4

Please sign in to comment.