using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame.Net
{
///
/// 서버와 기기 상태를 맞추는 일꾼(서버 모드에서 세션마다 1개).
/// 1. 접속: 서버 상태 확인 → 기준 정보(재화 목록) → 로그인 → 계정 수신 — 끝날 때까지 화면을 막는다.
/// 2. 전송: 기기에서 이미 반영한 동작을 **순서대로 하나씩** 서버에 보낸다(줄 세우기).
/// 3. 맞춤: 보낼 것이 없어지면 서버의 계정 상태를 다시 받아 기기 값을 덮는다 — 서버가 정본이다.
/// 4. 거절: 서버가 요청을 받아 주지 않으면(기기와 서버가 어긋남) 남은 요청을 버리고 서버 상태로 되돌린다.
/// 5. 끊김: 연결 문제는 몇 번 조용히 다시 보내고, 그래도 안 되면 화면을 막고 「다시 시도」를 받는다.
/// 6. 로그인: 저장한 증표로 이어 하기 → 없으면 로그인 화면(게스트 · 소셜). 다른 기기에서 같은 계정으로 접속하면 이쪽은 안내 뒤 타이틀로 돌아간다.
///
public class ServerSync : MonoBehaviour
{
public static ServerSync Instance { get; private set; }
public ServerClient Client { get; private set; }
/// 접속이 끝나 계정 상태를 받았는가.
public bool Ready { get; private set; }
/// 보내는 중이거나 보낼 것이 남았는가.
public bool Busy
{
get { return sending || queue.Count > 0; }
}
/// 서버 상태로 맞춘 횟수(접속 때 1회 제외).
public int Reconciles { get; private set; }
/// 서버가 거절한 횟수.
public int Rejects { get; private set; }
public string LastError { get; private set; }
/// 화면을 막는 안내가 떠 있는가.
public bool Blocking
{
get { return overlay != null && overlay.activeSelf; }
}
/// 세션을 잃어(다른 기기에서 접속 등) 타이틀로 돌아가는 안내가 떴는가.
public bool Kicked { get; private set; }
/// 화면을 막는 안내의 글(테스트 · 확인용).
public string OverlayMessage
{
get { return overlayText != null && Blocking ? overlayText.text : ""; }
}
class Item
{
public string method;
public string path;
/// 보내는 순간에 만든다(앞 요청의 응답 값 — 예: 전투 세션 — 을 쓸 수 있게).
public Func body;
public Action onOk;
public Action onReject;
/// 응답이 와야 화면을 채울 수 있는 요청(전투 종료 · 등용 · 상자 열기 …) — 오래 걸리면 안내를 띄운다.
public bool wait;
/// 응답을 받은 직후 서버의 계정 상태로 기기 값을 먼저 맞춘 다음 onOk 를 부른다(결과를 서버가 정하는 동작 — 화면이 맞춰진 값을 읽게).
public bool syncAfter;
/// 거절이 「기기와 서버가 어긋난 것」이 아닌 요청(쿠폰 코드 틀림 · 우편함 조회 …) — 거절돼도 뒤 요청을 버리지 않고 안내도 띄우지 않는다.
public bool soft;
}
readonly Queue- queue = new Queue
- ();
ServerSession session;
bool sending;
bool dirty;
float reconcileAt;
bool retryPressed;
float waitSince = -1f;
// 서버가 주간 랭킹 정산 중이라 입장을 거절했을 때의 이유 코드
const string SettleCode = "RANK_SETTLING";
// 안내 캔버스 = 다른 모든 화면(재화 바 450 · 타이틀 전환 960) 위 · 카메라에 가장 가까운 면
const int OverlayOrder = 990;
const float OverlayPlane = 0.3f;
GameObject overlay;
Text overlayText;
GameObject overlayButton;
Text overlayButtonLabel;
internal static ServerSync Create(ServerSession session)
{
if (Instance != null) Destroy(Instance.gameObject); // 씬을 다시 연 경우 — 앞 세션의 일꾼을 치운다
var go = new GameObject("ServerSync");
var s = go.AddComponent();
s.session = session;
s.Client = new ServerClient(ServerConfig.BaseUrl, ServerConfig.TimeoutSec, !ServerConfig.Forced);
Instance = s;
s.StartCoroutine(s.Run());
return s;
}
void OnDestroy()
{
if (Instance == this) Instance = null;
}
/// 요청을 줄 맨 뒤에 세운다. onReject = 서버가 거절했거나, 앞 요청이 거절돼 보내지 못하고 버려졌을 때.
internal void Post(string method, string path, Func body, Action onOk = null, Action onReject = null, bool wait = false, bool syncAfter = false, bool soft = false)
{
queue.Enqueue(new Item { method = method, path = path, body = body, onOk = onOk, onReject = onReject, wait = wait, syncAfter = syncAfter, soft = soft });
}
/// 보낼 것이 없어도 서버의 계정 상태를 한 번 다시 받는다(연무장 화면을 열 때 — 날짜 · 시즌이 넘어갔으면 서버가 맞춘 값이 온다).
internal void Refresh()
{
dirty = true;
reconcileAt = 0f;
}
IEnumerator Run()
{
yield return Connect();
while (true)
{
if (queue.Count == 0)
{
if (dirty && Time.unscaledTime >= reconcileAt) yield return Reconcile();
yield return null;
continue;
}
yield return SendNext();
}
}
// ---------- 접속 ----------
IEnumerator Connect()
{
var r = new ServerResult();
while (true)
{
ShowOverlay("서버에 접속하는 중…", false);
yield return Client.Send("GET", "/games/" + ServerConfig.GameId + "/status", null, false, r);
if (!r.ok)
{
yield return AskRetry("서버에 접속할 수 없습니다", r);
continue;
}
if (r.Str("status") != "NORMAL")
{
yield return AskRetry("서버 점검 중입니다 (" + r.Str("status") + ")", null);
continue;
}
yield return Client.Send("GET", "/tks/config", null, false, r);
if (!r.ok || !session.LoadGoodsTable(r))
{
yield return AskRetry("서버 기준 정보를 받지 못했습니다", r);
continue;
}
yield return Authenticate(r);
if (!r.ok)
{
yield return AskRetry("로그인하지 못했습니다", r);
continue;
}
ShowOverlay("서버에 접속하는 중…", false);
// 기기 시간대를 실어 보낸다 — 새 계정이면 서버가 이때 계정에 고정한다(일일 초기화 = 그 나라 0시)
yield return Client.Send("GET", ServerSession.AccountPath(), null, true, r);
if (!r.ok)
{
yield return AskRetry("계정 정보를 받지 못했습니다", r);
continue;
}
session.ApplySnapshot(r, true);
Ready = true;
HideOverlay();
yield break;
}
}
// ---------- 로그인 ----------
///
/// 로그인 — 기기에 저장한 증표가 있으면 그 계정으로 이어 하고(마지막에 로그인한 계정), 없거나 서버가 받지 않으면 로그인 화면을 띄운다.
/// 로그인 화면 = 게스트로 시작 · 소셜 계정(구글 플레이 · 게임센터)으로 로그인. 끝나면 r.ok (연결 문제면 r.network).
///
IEnumerator Authenticate(ServerResult r)
{
if (ServerLink.AutoLogin)
{
yield return Client.Login(ServerConfig.GameId, r); // 테스트: 화면 없이 이어 하기 → 없으면 새 게스트
yield break;
}
string notice = null;
if (Client.HasSaved)
{
yield return Client.Resume(r);
if (r.ok || r.network) yield break;
notice = "로그인 정보가 만료되었거나 다른 기기에서 접속했습니다.\n다시 로그인해 주세요.";
Client.Forget();
}
while (true)
{
HideOverlay();
string method = null, socialId = null;
var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main;
LoginPanel.Show(transform, cam, Client.LastMethod, Client.LastSocialId, notice, (m, id) =>
{
method = m;
socialId = id;
});
while (method == null) yield return null;
LoginPanel.Close();
ShowOverlay("로그인하는 중…", false);
if (method == ServerClient.MethodGuest) yield return Client.GuestLogin(ServerConfig.GameId, r);
else
{
string credential = null, error = null;
bool done = false;
SocialSignIn.SignIn(method, socialId, (c, e) =>
{
credential = c;
error = e;
done = true;
});
while (!done) yield return null;
if (credential == null)
{
notice = error;
continue;
}
yield return Client.SocialLogin(ServerConfig.GameId, method, credential, socialId, r);
}
if (r.ok || r.network) yield break;
notice = "로그인하지 못했습니다 (" + (string.IsNullOrEmpty(r.Message) ? r.error : r.Message) + ")";
}
}
///
/// 세션을 잃었다(다른 기기에서 이 계정으로 접속 · 삭제된 계정 · 증표 만료) — 줄 선 요청을 버리고 안내한 뒤 타이틀(로그인 화면)로 돌아간다.
/// 한 계정은 한 기기에서만 접속한다(PD 2026-11-17).
///
IEnumerator Kick()
{
var dropped = queue.ToArray();
queue.Clear();
sending = false;
waitSince = -1f;
Ready = false;
Kicked = true;
string reason = Client.LostReason;
LastError = "세션 종료: " + reason;
Debug.LogWarning("[TKS] " + LastError);
var lost = new ServerResult { ok = false, status = 401, error = LastError };
foreach (var d in dropped)
if (d.onReject != null) d.onReject(lost);
Client.Forget();
string msg = reason == ServerClient.LostReplaced ? "다른 기기에서 이 계정으로 접속하여\n연결이 종료되었습니다."
: reason == ServerClient.LostDeleted ? "삭제된 계정입니다."
: "로그인 정보가 만료되었습니다.";
retryPressed = false;
ShowOverlay(msg + "\n확인을 누르면 타이틀 화면으로 돌아갑니다", true, "확인");
while (!retryPressed) yield return null;
ServerLink.Restart();
while (true) yield return null; // 씬이 바뀔 때까지
}
// ---------- 계정 (옵션 화면이 부른다) ----------
/// 지금 로그인한 계정의 로그인 정보(게스트인가 · 어느 소셜 계정인가).
public void AccountInfo(Action done)
{
Post("GET", "/auth/session", null, done, done, false, false, true);
}
/// 로그아웃(소셜 계정) → 타이틀의 로그인 화면으로. 실패하면 fail(이유).
public void Logout(Action fail)
{
StartCoroutine(Leave(false, fail));
}
/// 계정 삭제(게스트) → 서버가 데이터를 지우고, 기기의 로그인 상태를 초기화한 뒤 타이틀의 로그인 화면으로.
public void DeleteAccount(Action fail)
{
StartCoroutine(Leave(true, fail));
}
IEnumerator Leave(bool delete, Action fail)
{
while (Busy) yield return null; // 줄 선 요청을 먼저 다 보낸다
ShowOverlay(delete ? "계정을 삭제하는 중…" : "로그아웃하는 중…", false);
var r = new ServerResult();
if (delete) yield return Client.DeleteAccount(r);
else yield return Client.Logout(r);
HideOverlay();
if (!r.ok)
{
if (fail != null) fail(r.network ? "서버와 연결되지 않았습니다" : r.Message);
yield break;
}
Ready = false;
ServerLink.Restart();
}
///
/// 게스트 계정을 소셜 계정에 연동. done(r): r.ok = 끝(연동됨 · 또는 기존 계정으로 들어감 → 타이틀로 다시 시작) ·
/// r.status 409 = 그 소셜 계정이 이미 다른 게임 계정에 연동돼 있다(r 에 current · existing 요약) → 유저가 고른 뒤 resolve 를 붙여 다시 부른다 · 그 밖 = 실패.
///
public void Link(string method, string socialId, string resolve, Action done)
{
StartCoroutine(LinkRoutine(method, socialId, resolve, done));
}
IEnumerator LinkRoutine(string method, string socialId, string resolve, Action done)
{
while (Busy) yield return null;
var r = new ServerResult();
string credential = null, error = null;
bool signed = false;
SocialSignIn.SignIn(method, socialId, (c, e) =>
{
credential = c;
error = e;
signed = true;
});
while (!signed) yield return null;
if (credential == null)
{
r.error = error;
done(r);
yield break;
}
ShowOverlay("계정을 연동하는 중…", false);
yield return Client.Link(method, credential, socialId, resolve, r);
HideOverlay();
if (r.ok && r.Str("result") == LinkSwitched)
{
// 기존 연동 계정으로 들어갔다 — 그 계정의 데이터로 다시 시작한다
done(r);
Ready = false;
ServerLink.Restart();
yield break;
}
if (r.ok) Refresh();
done(r);
}
// 연동 응답의 result 값 — 기존 연동 계정으로 들어갔을 때
const string LinkSwitched = "switched";
// ---------- 전송 ----------
IEnumerator SendNext()
{
var it = queue.Peek();
sending = true;
var r = new ServerResult();
int tries = 0;
if (it.wait) waitSince = Time.unscaledTime;
while (true)
{
yield return Client.Send(it.method, it.path, it.body != null ? it.body() : null, true, r);
if (r.ok || !r.network) break;
if (tries < ServerConfig.Retry)
{
tries++;
yield return new WaitForSecondsRealtime(0.5f * tries);
continue;
}
yield return AskRetry("서버와 연결이 끊겼습니다", r); // 「다시 시도」 = 같은 요청을 다시 보낸다
tries = 0;
}
waitSince = -1f;
HideOverlay();
if (Client.LostReason != null)
{
yield return Kick(); // 다른 기기에서 접속했다 등 — 타이틀로 돌아간다
yield break;
}
queue.Dequeue();
sending = false;
if (r.ok)
{
if (it.syncAfter)
{
sending = true; // 맞추는 동안도 「보내는 중」
if (it.wait) waitSince = Time.unscaledTime;
yield return Reconcile(true);
waitSince = -1f;
HideOverlay();
sending = false;
}
if (it.onOk != null) it.onOk(r);
dirty = true;
reconcileAt = Time.unscaledTime + ServerConfig.ReconcileDelay;
yield break;
}
if (it.soft)
{
// 어긋난 것이 아닌 거절(쿠폰 코드 틀림 등) — 그 요청만 실패로 알리고 줄은 그대로 둔다
if (it.onReject != null) it.onReject(r);
yield break;
}
// 서버가 거절 = 기기와 서버가 어긋났다 → 뒤에 줄 선 요청은 어긋난 상태에서 만든 것이라 버리고 서버 상태로 되돌린다
Rejects++;
LastError = it.method + " " + it.path + " → " + r.error;
Debug.LogWarning("[TKS] 서버가 요청을 거절했습니다: " + LastError);
var dropped = queue.ToArray();
queue.Clear();
if (it.onReject != null) it.onReject(r);
foreach (var d in dropped)
if (d.onReject != null) d.onReject(r);
dirty = true;
reconcileAt = 0f;
yield return Reconcile();
Notice(r.Message == SettleCode ? ArenaRules.SettleNotice : "서버 기록과 달라 다시 불러왔습니다 (" + r.Message + ")");
}
/// 서버의 계정 상태로 기기 값을 덮는다. 받는 사이에 새 요청이 줄 섰으면 버리고 다음에 다시 한다(force = 줄이 있어도 덮는다).
IEnumerator Reconcile(bool force = false)
{
var r = new ServerResult();
yield return Client.Send("GET", "/tks/account", null, true, r);
if (Client.LostReason != null)
{
yield return Kick();
yield break;
}
if (!r.ok)
{
reconcileAt = Time.unscaledTime + Mathf.Max(1f, ServerConfig.ReconcileDelay) * 3f; // 조금 뒤에 다시
yield break;
}
if (queue.Count > 0 && !force) yield break;
session.ApplySnapshot(r, false);
dirty = false;
Reconciles++;
}
void Update()
{
// 응답을 기다려야 하는 요청이 오래 걸리면 안내
if (waitSince >= 0f && !Blocking && Time.unscaledTime - waitSince >= ServerConfig.WaitNotice) ShowOverlay("서버에 기록하는 중…", false);
}
// ---------- 안내 ----------
static void Notice(string msg)
{
if (OutGameRoot.Instance != null) OutGameRoot.Instance.Toast(msg);
}
IEnumerator AskRetry(string msg, ServerResult r)
{
LastError = msg + (r != null && !string.IsNullOrEmpty(r.error) ? " — " + r.error : "");
Debug.LogWarning("[TKS] " + LastError);
retryPressed = false;
ShowOverlay(msg + (r != null && !string.IsNullOrEmpty(r.error) ? "\n" + r.error + "" : ""), true);
while (!retryPressed) yield return null;
}
/// 「다시 시도」 누름(화면 버튼 · 테스트).
public void PressRetry()
{
retryPressed = true;
}
void ShowOverlay(string msg, bool button, string buttonLabel = "다시 시도")
{
if (overlay == null) BuildOverlay();
overlayText.text = msg;
overlayButton.SetActive(button);
if (overlayButtonLabel != null) overlayButtonLabel.text = buttonLabel;
overlay.SetActive(true);
}
void HideOverlay()
{
if (overlay != null) overlay.SetActive(false);
}
/// 화면 전체를 덮어 누름을 막는 안내(가끔만 뜨고 평소엔 꺼 둔다 · 자기 캔버스 1개 = 사건 때만 바뀌는 층).
void BuildOverlay()
{
overlay = new GameObject("ServerOverlay");
overlay.transform.SetParent(transform, false);
var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main;
UiLayer.Root(overlay, cam, OverlayOrder, OverlayPlane, OutGameRoot.Reference, UiRate.Event);
var dim = UiKit.Fill("Dim", overlay.transform);
var img = dim.gameObject.AddComponent();
img.color = new Color(0f, 0f, 0f, 0.72f);
img.raycastTarget = true; // 아래 화면 누름 막기
var center = new Vector2(0.5f, 0.5f);
overlayText = UiKit.Label(dim, "", 36, Color.white, TextAnchor.MiddleCenter, center, center, new Vector2(0f, 60f), new Vector2(900f, 260f));
overlayText.supportRichText = true;
var btn = new GameObject("Retry", typeof(RectTransform), typeof(Image), typeof(Button));
btn.transform.SetParent(dim, false);
var rt = (RectTransform)btn.transform;
rt.anchorMin = rt.anchorMax = rt.pivot = center;
rt.anchoredPosition = new Vector2(0f, -150f);
rt.sizeDelta = new Vector2(360f, 110f);
btn.GetComponent().color = UiKit.Red;
btn.GetComponent