WebGL 용 코드 추가

This commit is contained in:
logonkhi
2025-11-10 16:38:43 +09:00
parent f3d950fce7
commit 9277bab6dd
14 changed files with 433 additions and 35 deletions

View File

@@ -256,9 +256,11 @@ namespace UVC.Network
bool isMainThread = PlayerLoopHelper.IsMainThread;
//var response = await request.GetFromJsonResultAsync<T>();
var response = await request.GetAsStringAsync();
if(!isMainThread) await UniTask.SwitchToThreadPool();
#if !UNITY_WEBGL || UNITY_EDITOR
if (!isMainThread) await UniTask.SwitchToThreadPool();
log.ResponseData = response;
log.ResponseDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
#endif
ServerLog.LogHttpResponse(log);
//T가 string이면
if (typeof(T) == typeof(string))
@@ -423,7 +425,9 @@ namespace UVC.Network
var now = DateTime.UtcNow;
bool isMainThread = PlayerLoopHelper.IsMainThread;
var response = await request.GetAsStringAsync();
#if !UNITY_WEBGL || UNITY_EDITOR
if (!isMainThread) await UniTask.SwitchToThreadPool();
#endif
var diff = DateTime.UtcNow - now;
log.ResponseData = response;
log.ResponseDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
@@ -495,8 +499,22 @@ namespace UVC.Network
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
//System.IO.File.WriteAllBytes(savePath, resp.Data);
#if UNITY_WEBGL && !UNITY_EDITOR
// WebGL: 백그라운드 쓰레드 불가 -> 완료 시 메모리 데이터로 파일 저장
try
{
System.IO.File.WriteAllBytes(savePath, resp.Data);
OnComplete?.Invoke();
}
catch (Exception ex)
{
ULog.Error($"Failed to write file on WebGL: {ex.Message}", ex);
OnError?.Invoke($"Failed to write file: {ex.Message}");
}
#else
//스트리밍 파일 기록은 OnDownloadStarted에서 처리됨
OnComplete.Invoke();
#endif
}
else
{
@@ -515,6 +533,15 @@ namespace UVC.Network
};
var request = SelectHTTPRequest(HTTPMethods.Get, url, onRequest);
#if UNITY_WEBGL && !UNITY_EDITOR
// WebGL: 쓰레드 기반 스트리밍 미사용. 진행률 콜백만 연결.
request.DownloadSettings.OnDownloadProgress += (HTTPRequest req, long progress, long length) =>
{
ULog.Debug($"Download Progress! progress:{progress} length:{length}");
OnProgress?.Invoke(progress, length);
};
// DownloadStreamFactory/BlockingDownloadContentStream 사용 금지
#else
request.DownloadSettings.OnDownloadStarted += async (HTTPRequest req, HTTPResponse resp, DownloadContentStream stream) =>
{
@@ -533,7 +560,7 @@ namespace UVC.Network
};
request.DownloadSettings.DownloadStreamFactory = (req, resp, bufferAvailableHandler)
=> new BlockingDownloadContentStream(resp, req.DownloadSettings.ContentStreamMaxBuffered, bufferAvailableHandler);
#endif
return request.Send();
}

View File

@@ -1,4 +1,4 @@
using Best.MQTT;
using Best.MQTT;
using Best.MQTT.Packets.Builders;
using Cysharp.Threading.Tasks;
using System;
@@ -16,6 +16,7 @@ namespace UVC.network
/// <remarks>
/// 이 클래스는 스레드 안전한 방식으로 토픽 핸들러를 관리하며, 연결 끊김 시 자동 재연결 기능을 제공합니다.
/// 내부적으로 Best.MQTT 라이브러리를 사용하여 MQTT 프로토콜 통신을 구현합니다.
/// WebGL 플랫폼에서는 스레드풀이 지원되지 않으므로, 메시지 핸들러는 메인 스레드에서 실행됩니다.
/// </remarks>
public class MQTTService
{
@@ -321,26 +322,32 @@ namespace UVC.network
/// </remarks>
private void OnTopic(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message)
{
// 메인 스레드에서 실행 중인지 확인합니다.
bool isMainThread = PlayerLoopHelper.IsMainThread;
//Debug.Log($"MQTT OnTopic isMainThread={isMainThread}, onBackgroundThread:{onBackgroundThread}, {topic.Filter.OriginalFilter}");
if (isMainThread && onBackgroundThread)
DispatchTopic(() => OnTopicLogic(client, topic, topicName, message));
}
// 웹GL 대응: 스레드풀 미지원 시 메인 스레드로 포스트
private void DispatchTopic(Action work)
{
#if UNITY_WEBGL && !UNITY_EDITOR
// WebGL: 스레드풀 없음 → 다음 프레임에 메인 스레드로 실행
UniTask.Post(work);
#else
if (onBackgroundThread)
{
// 백그라운드 스레드에서 실행
UniTask.RunOnThreadPool(() => OnTopicLogic(client, topic, topicName, message)).Forget();
}
else if (!isMainThread && !onBackgroundThread)
{
// 메인 스레드에서 실행
UniTask.Post(() => OnTopicLogic(client, topic, topicName, message));
UniTask.RunOnThreadPool(work).Forget();
}
else
{
// 메인 스레드에서 실행
OnTopicLogic(client, topic, topicName, message);
if (PlayerLoopHelper.IsMainThread)
work();
else
UniTask.Post(work);
}
#endif
}
private void OnTopicLogic(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message)
{
//Debug.Log($"MQTT OnTopicLogic isMainThread={PlayerLoopHelper.IsMainThread}");