TCP 양방향 통신으로 만드는 1:1 틱택토 게임 (Java Server + Unity Client)

김해준's avatar
Dec 17, 2025
TCP 양방향 통신으로 만드는 1:1 틱택토 게임 (Java Server + Unity Client)
notion image

1. 개요

이번 글에서는 TCP 소켓 기반 양방향 통신(Full-Duplex) 구조를 이용해
Java 서버 + Unity 클라이언트로 동작하는 1:1 틱택토 게임을 구현한 과정을 정리한다.
목표는 다음과 같다.
  • TCP 기반 서버 권한(authoritative) 구조 이해
  • 송신/수신 분리된 양방향 통신 흐름 구현
  • Unity에서 네트워크 게임 상태를 안전하게 UI에 반영
  • 짧은 시간 안에 테스트 가능한 미니 멀티플레이 게임 완성

2. 전체 구조

📌 서버 (Java)

  • TCP ServerSocket 기반
  • 최대 2명 접속
  • 접속 순서대로 Player1 / Player2 지정
  • 게임 상태(보드, 턴, 승패)는 서버가 단독 관리
package com.mtcoding.TicTacToe; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /* * TicTacToeServer.java * ------------------------------------------------------------ * 역할 분리 * 1) TicTacToeServer : 접속/세션관리/브로드캐스트/흐름 * 2) ClientSession : 클라이언트 1명 소켓 송수신 * 3) TicTacToeGame : 보드/턴/승패 판정 (네트워크와 분리) */ public class TicTacToeServer { // ============================================================ // [Config] // ============================================================ private static final int PORT = 20000; // ============================================================ // [Server State] // ============================================================ private final List<ClientSession> sessions = new CopyOnWriteArrayList<>(); private final TicTacToeGame game = new TicTacToeGame(); public static void main(String[] args) { new TicTacToeServer().run(); } // ============================================================ // [Server Main Loop] // ============================================================ private void run() { try (ServerSocket ss = new ServerSocket(PORT)) { System.out.println("[server] listening on " + PORT); while (true) { Socket socket = ss.accept(); System.out.println("[server] connected: " + socket.getInetAddress()); // 2명 제한(간단 구현) if (sessions.size() >= 2) { try (PrintWriter temp = new PrintWriter(socket.getOutputStream(), true)) { temp.println("INFO server full (only 2 players)"); } catch (Exception ignored) {} try { socket.close(); } catch (Exception ignored) {} continue; } // ------------------------------------------------------------ // 1) 접속 순서대로 PlayerNo/Mark 배정 // Player1 = X, Player2 = O // ------------------------------------------------------------ int playerNo = (sessions.size() == 0) ? 1 : 2; char mark = (playerNo == 1) ? 'X' : 'O'; ClientSession session = new ClientSession(socket, mark, this); sessions.add(session); // ------------------------------------------------------------ // 2) 세션 스레드 먼저 시작 (안전) // ------------------------------------------------------------ new Thread(session).start(); // ------------------------------------------------------------ // 3) 초기 안내 (PlayerNo/Mark) // ------------------------------------------------------------ session.send("PLAYER " + playerNo); session.send("ASSIGN " + mark); // ------------------------------------------------------------ // 4) 대기 / 시작 처리 // ------------------------------------------------------------ if (sessions.size() < 2) { session.send("WAIT"); broadcast("INFO player joined: " + mark + " (waiting...)"); } else { // 2명 다 모이면 새 게임 시작 game.reset(); // ✅ 중요: 재접속/재시작 테스트 편하게 broadcast("INFO player joined: " + mark); broadcast("START"); broadcast("STATE " + game.getStateString()); broadcast("TURN " + game.getCurrentTurn()); } } } catch (Exception e) { e.printStackTrace(); } } // ============================================================ // [Called by Session] // ============================================================ void onHello(ClientSession from, String name) { from.setName(name); System.out.println("Player "+name+" Connect."); from.send("INFO hello " + name); } void onPut(ClientSession from, int r, int c) { // 상대 기다리기 if (sessions.size() < 2) { from.send("ERR wait for opponent"); return; } TicTacToeGame.PutResult result = game.tryPut(from.getMark(), r, c); if (!result.ok) { from.send("ERR " + result.message); return; } // 상태 방송 broadcast("STATE " + game.getStateString()); // 게임 종료 체크 if (result.winner != TicTacToeGame.EMPTY) { broadcast("WIN " + result.winner); return; } if (result.draw) { broadcast("DRAW"); return; } // 턴 방송 broadcast("TURN " + game.getCurrentTurn()); } void onDisconnect(ClientSession session) { sessions.remove(session); broadcast("INFO player left: " + session.getMark()); // 간단 처리: 누가 나가면 게임 중단 game.stop(); broadcast("INFO game stopped"); } void onRestart(ClientSession from) { if (sessions.size() < 2) { from.send("ERR wait for opponent"); return; } game.reset(); // 이미 넣어둔 reset() 사용 broadcast("INFO restart"); broadcast("START"); broadcast("STATE " + game.getStateString()); broadcast("TURN " + game.getCurrentTurn()); } // ============================================================ // [Broadcast] // ============================================================ private void broadcast(String msg) { for (ClientSession s : sessions) s.send(msg); } }
package com.mtcoding.TicTacToe; import java.util.Arrays; // ============================================================ // 3) TicTacToeGame : 게임 상태/규칙(네트워크와 분리) // ============================================================ public class TicTacToeGame { static final char EMPTY = '.'; private final char[] board = new char[9]; private char currentTurn = 'X'; private boolean gameOver = false; TicTacToeGame() { Arrays.fill(board, EMPTY); } static class PutResult { boolean ok; String message; char winner = EMPTY; boolean draw = false; } synchronized char getCurrentTurn() { return currentTurn; } synchronized String getStateString() { return new String(board); } synchronized void stop() { gameOver = true; } synchronized PutResult tryPut(char mark, int r, int c) { PutResult res = new PutResult(); System.out.println(mark + " put x : "+r+" y : "+c); if (gameOver) { res.ok = false; res.message = "game over"; return res; } if (mark != currentTurn) { res.ok = false; res.message = "not your turn"; return res; } if (r < 0 || r > 2 || c < 0 || c > 2) { res.ok = false; res.message = "out of range"; return res; } int idx = r * 3 + c; if (board[idx] != EMPTY) { res.ok = false; res.message = "cell not empty"; return res; } board[idx] = mark; int index = 0; for(int i = 0; i < 3; i++) { for(int j = 0 ; j < 3; j++) { System.out.print(board[index]+" "); index++; } System.out.println(); } // 승/무 체크 char w = checkWinner(); if (w != EMPTY) { gameOver = true; res.ok = true; res.winner = w; return res; } if (isDraw()) { gameOver = true; res.ok = true; res.draw = true; return res; } // 턴 교체 currentTurn = (currentTurn == 'X') ? 'O' : 'X'; res.ok = true; return res; } private char checkWinner() { int[][] lines = { {0,1,2},{3,4,5},{6,7,8}, {0,3,6},{1,4,7},{2,5,8}, {0,4,8},{2,4,6} }; for (int[] l : lines) { char a = board[l[0]]; if (a == EMPTY) continue; if (a == board[l[1]] && a == board[l[2]]) return a; } return EMPTY; } private boolean isDraw() { for (char v : board) if (v == EMPTY) return false; return true; } synchronized void reset() { Arrays.fill(board, EMPTY); currentTurn = 'X'; gameOver = false; } }
package com.mtcoding.TicTacToe; import java.io.*; import java.net.Socket; // ============================================================ // 2) ClientSession : 소켓 1명 처리(송수신), 프로토콜 파싱 // ============================================================ public class ClientSession implements Runnable{ private final Socket socket; private final BufferedReader br; private final PrintWriter pw; private final char mark; private String name = "anon"; private final TicTacToeServer server; ClientSession(Socket socket, char mark, TicTacToeServer server) throws IOException { this.socket = socket; this.mark = mark; this.server = server; this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true); } char getMark() { return mark; } void setName(String name) { this.name = name; } String getName() { return name; } void send(String msg) { pw.println(msg); } @Override public void run() { try { String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; // HELLO name if (line.startsWith("HELLO ")) { server.onHello(this, line.substring(6).trim()); continue; } // PUT r c if (line.startsWith("PUT ")) { String[] sp = line.split("\\s+"); if (sp.length != 3) { send("ERR PUT format: PUT r c"); continue; } int r = Integer.parseInt(sp[1]); int c = Integer.parseInt(sp[2]); server.onPut(this, r, c); continue; } // RESTART if (line.equalsIgnoreCase("RESTART")) { System.out.println("Call ReStart"); server.onRestart(this); continue; } // QUIT if (line.equalsIgnoreCase("QUIT")) { System.out.println("Call Quit"); break; } send("ERR unknown command"); } } catch (Exception e) { System.out.println("[server] session error(" + mark + "): " + e.getMessage()); } finally { close(); server.onDisconnect(this); } } private void close() { try { socket.close(); } catch (Exception ignored) {} } }

📌 클라이언트 (Unity)

  • TCP Client
  • GameManager 싱글톤으로 흐름 관리
  • 네트워크 수신은 별도 스레드
  • UI 갱신은 메인 스레드에서만 처리
using System; using TMPro; using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { // ============================================================ // [Singleton] // ============================================================ public static GameManager Instance { get; private set; } void Awake() { // 싱글톤 보장 if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); Application.runInBackground = true; InitOnce(); } // ============================================================ // [Lobby UI] // ============================================================ [Header("Lobby UI")] public GameObject lobbyPanel; public TMP_InputField ipInput; public TMP_InputField portInput; public TMP_InputField nameInput; public Button connectButton; // ============================================================ // [Game UI] // ============================================================ [Header("Game UI")] public GameObject gamePanel; public Button[] cells; // 9 buttons public TextMeshProUGUI statusText; public Sprite[] sprites; // 0 - O / 1 - X public Button restartButton; // ============================================================ // [Services] // ============================================================ TcpClientService net; BoardView boardView; // ============================================================ // [Client/Game State] // ============================================================ enum State { Lobby, WaitingOpponent, InGame, End } State state = State.Lobby; int myPlayerNo = 0; // 1 or 2 char myMark = '?'; // X or O char currentTurn = '?'; char[] board = new char[9]; bool gameEnded = false; bool initialized = false; // ============================================================ // [Init] // ============================================================ void InitOnce() { if (initialized) return; initialized = true; for (int i = 0; i < 9; i++) board[i] = '.'; // BoardView 구성 boardView = gameObject.AddComponent<BoardView>(); boardView.cells = cells; boardView.statusText = statusText; boardView.Init(); boardView.OnCellClicked += OnCellClicked; // Network 구성 net = new TcpClientService(); net.OnMessage += HandleServerMessage; net.OnError += (e) => SetStatus("[error] " + e); net.OnDisconnected += () => { SetStatus("disconnected"); EnterLobby(); // 끊기면 로비로 }; connectButton.onClick.AddListener(OnClickConnect); restartButton.onClick.AddListener(OnClickRestart); restartButton.gameObject.SetActive(false); EnterLobby(); } // ============================================================ // [Unity] // ============================================================ void Update() { net?.Pump(); } void OnDestroy() { if (Instance == this) Instance = null; try { net?.SendLine("QUIT"); } catch { } net?.Disconnect(); } // ============================================================ // [Flow] // ============================================================ void EnterLobby() { state = State.Lobby; lobbyPanel.SetActive(true); gamePanel.SetActive(false); gameEnded = false; myPlayerNo = 0; myMark = '?'; currentTurn = '?'; SetStatus("Input IP/Port And Click Connect."); } void EnterWaiting() { state = State.WaitingOpponent; lobbyPanel.SetActive(false); gamePanel.SetActive(true); gameEnded = false; for (int i = 0; i < 9; i++) board[i] = '.'; boardView.RenderBoard(board, sprites); boardView.DisableAll(); SetStatus("Connected. Wait..."); restartButton.gameObject.SetActive(false); } void EnterGame() { state = State.InGame; gameEnded = false; SetStatus($"GameStart. Im P{myPlayerNo}({myMark})"); RefreshInteractable(); restartButton.gameObject.SetActive(false); } void EnterEnd(string result) { state = State.End; gameEnded = true; SetStatus(result); boardView.DisableAll(); restartButton.gameObject.SetActive(true); } // ============================================================ // [Lobby -> Connect] // ============================================================ void OnClickConnect() { string host = ipInput != null ? ipInput.text.Trim() : "127.0.0.1"; string portStr = portInput != null ? portInput.text.Trim() : "20000"; string name = nameInput != null ? nameInput.text.Trim() : "player"; if (string.IsNullOrEmpty(host)) host = "127.0.0.1"; if (string.IsNullOrEmpty(portStr)) portStr = "20000"; if (string.IsNullOrEmpty(name)) name = "player"; if (!int.TryParse(portStr, out int port)) { SetStatus("Port is Not Number."); return; } // 재접속 대비 초기화 net.Disconnect(); myPlayerNo = 0; myMark = '?'; currentTurn = '?'; gameEnded = false; SetStatus("connecting..."); net.Connect(host, port); // 인사 net.SendLine("HELLO " + name); // WAIT/START는 서버 메시지로 확정되므로 일단 대기 화면으로 EnterWaiting(); } // ============================================================ // [Board Click -> PUT] // ============================================================ void OnCellClicked(int idx) { if (state != State.InGame) return; if (gameEnded) return; if (myMark == '?' || currentTurn != myMark) return; if (board[idx] != '.') return; int r = idx / 3; int c = idx % 3; net.SendLine($"PUT {r} {c}"); } void OnClickRestart() { net.SendLine("RESTART"); restartButton.gameObject.SetActive(false); SetStatus("restart ..."); } // ============================================================ // [Server -> Client Protocol] // ============================================================ void HandleServerMessage(string msg) { // PLAYER 1 if (msg.StartsWith("PLAYER ")) { if (int.TryParse(msg.Substring(7).Trim(), out int no)) myPlayerNo = no; SetStatus($"Player Number : P{myPlayerNo}"); return; } // ASSIGN X if (msg.StartsWith("ASSIGN ")) { myMark = msg.Substring(7).Trim()[0]; SetStatus($"Player Button : {myMark}"); return; } // WAIT if (msg == "WAIT") { // 이미 Waiting이면 유지 if (state != State.WaitingOpponent) EnterWaiting(); return; } // START if (msg == "START") { EnterGame(); return; } // STATE X..O..X.. if (msg.StartsWith("STATE ")) { string s = msg.Substring(6).Trim(); if (s.Length == 9) { for (int i = 0; i < 9; i++) board[i] = s[i]; // ✅ 그대로 sprites 넘기기 boardView.RenderBoard(board, sprites); RefreshInteractable(); } return; } // TURN X if (msg.StartsWith("TURN ")) { currentTurn = msg.Substring(5).Trim()[0]; SetStatus($"Turn: {currentTurn} / Im: {myMark}"); RefreshInteractable(); return; } // WIN X if (msg.StartsWith("WIN ")) { char w = msg.Substring(4).Trim()[0]; EnterEnd(w == myMark ? "YOU WIN" : "YOU LOSE"); return; } // DRAW if (msg == "DRAW") { EnterEnd("DRAW"); return; } // INFO / ERR if (msg.StartsWith("INFO ")) { SetStatus(msg.Substring(5)); return; } if (msg.StartsWith("ERR ")) { SetStatus("error: " + msg.Substring(4)); return; } } // ============================================================ // [UI Helper] // ============================================================ void RefreshInteractable() { bool[] interactable = new bool[9]; bool myTurn = (state == State.InGame) && (!gameEnded) && (myMark != '?') && (currentTurn == myMark); for (int i = 0; i < 9; i++) interactable[i] = myTurn && (board[i] == '.'); boardView.SetInteractable(interactable); } void SetStatus(string s) { if (statusText != null) statusText.text = s; Debug.Log("[GM] " + s); } }
using System; using TMPro; using UnityEngine; using UnityEngine.UI; public class BoardView : MonoBehaviour { public Button[] cells; // size 9 public TextMeshProUGUI statusText; public event Action<int> OnCellClicked; public void Init() { for (int i = 0; i < 9; i++) { int idx = i; cells[i].onClick.AddListener(() => OnCellClicked?.Invoke(idx)); } } public void SetStatus(string msg) { if (statusText != null) statusText.text = msg; } public void RenderBoard(char[] board, Sprite[] sprites) { for (int i = 0; i < 9; i++) { Image img = cells[i].GetComponentInChildren<Image>(true); if (img == null) continue; char v = board[i]; if (v == '.') { img.sprite = sprites[0]; img.enabled = true; } else if (v == 'O') { img.sprite = sprites[1]; img.enabled = true; } else if (v == 'X') { img.sprite = sprites[2]; img.enabled = true; } } } public void SetInteractable(bool[] interactable) { for (int i = 0; i < 9; i++) cells[i].interactable = interactable[i]; } public void DisableAll() { for (int i = 0; i < 9; i++) cells[i].interactable = false; } }
using System; using System.Collections.Concurrent; using System.IO; using System.Net.Sockets; using System.Threading; public class TcpClientService { public event Action<string> OnMessage; // main thread public event Action<string> OnError; // main thread public event Action OnDisconnected; // main thread TcpClient client; StreamReader reader; StreamWriter writer; Thread recvThread; volatile bool running; readonly ConcurrentQueue<Action> mainJobs = new ConcurrentQueue<Action>(); public bool IsConnected => client != null && client.Connected; public void Connect(string host, int port) { try { client = new TcpClient(); client.Connect(host, port); var stream = client.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream) { AutoFlush = true }; running = true; recvThread = new Thread(RecvLoop) { IsBackground = true }; recvThread.Start(); } catch (Exception e) { EnqueueMain(() => OnError?.Invoke("connect failed: " + e.Message)); } } public void SendLine(string msg) { try { writer?.WriteLine(msg); } catch (Exception e) { EnqueueMain(() => OnError?.Invoke("send failed: " + e.Message)); } } public void Disconnect() { running = false; try { client?.Close(); } catch { } client = null; } public void Pump() { while (mainJobs.TryDequeue(out var job)) job?.Invoke(); } void RecvLoop() { try { while (running) { string line = reader.ReadLine(); // blocking if (line == null) break; string msg = line.Trim(); if (msg.Length == 0) continue; EnqueueMain(() => OnMessage?.Invoke(msg)); } } catch (Exception e) { EnqueueMain(() => OnError?.Invoke("recv failed: " + e.Message)); } finally { EnqueueMain(() => OnDisconnected?.Invoke()); Disconnect(); } } void EnqueueMain(Action a) => mainJobs.Enqueue(a); }
[ UnityClient ] ←→ [ Java TCPServer ] ←→ [ UnityClient ]

3. 통신 프로토콜 설계

텍스트 기반의 단순한 프로토콜을 사용했다.

Client → Server

  • HELLO <name> : 접속 인사
  • PUT r c : r,c 위치에 돌 두기
  • RESTART : 게임 재시작 요청
  • QUIT : 종료

Server → Client

  • PLAYER 1 | 2 : 플레이어 번호
  • ASSIGN X | O : 말 배정
  • WAIT : 상대 대기
  • START : 게임 시작
  • STATE <9chars> : 보드 상태
  • TURN X | O : 현재 턴
  • WIN X | O
  • DRAW
  • INFO / ERR

4. 서버 설계 (Java)

서버는 역할을 명확히 분리했다.

역할 분리

  • TicTacToeServer
    • 접속 관리
    • 브로드캐스트
    • 게임 흐름 제어
  • ClientSession
    • 클라이언트 1명당 소켓 입출력 처리
  • TicTacToeGame
    • 보드 상태
    • 턴 관리
    • 승패 판정
    • reset()
게임 로직은 네트워크 코드와 완전히 분리하여,
테스트와 유지보수가 쉬운 구조로 설계했다.

5. Unity 클라이언트 구조

5.1 GameManager (Singleton)

  • 게임 전체 흐름을 관리하는 중앙 관리자
  • Lobby → Waiting → InGame → End 상태 전환
  • 서버 메시지 해석 및 상태 반영
  • DontDestroyOnLoad 적용
publicstatic GameManager Instance {get;privateset; }

5.2 TcpClientService

  • TCP 연결 / 송신 / 수신 담당
  • 수신은 백그라운드 스레드
  • 메시지는 Queue에 쌓아 Update()에서 처리
Unity의 메인 스레드 규칙을 지키기 위한 구조다.

5.3 BoardView

  • 3×3 버튼 UI 담당
  • 렌더링만 담당 (로직 없음)
  • GameManager가 전달한 상태를 그대로 그린다

6. 보드 렌더링 방식 (Sprite 기반)

문자(X/O) 대신 Sprite로 보드를 표현했다.
sprites[0] = Empty sprites[1] = O sprites[2] = X
이 구조의 장점:
  • Image enable/disable 관리 불필요
  • 항상 sprite만 교체
  • 이후 애니메이션/이펙트 확장 용이
boardView.RenderBoard(board, sprites);

7. 백그라운드 멈춤 문제 해결

Unity 빌드 2개를 띄워 테스트 시
포커스를 잃은 클라이언트가 멈추는 문제가 발생했다.
원인은:
  • Unity가 기본적으로 백그라운드 Update를 중단하기 때문

해결 코드

Application.runInBackground =true;
이를 통해 두 클라이언트가 동시에 정상 동작하도록 했다.

8. 게임 리스타트 기능

게임 종료 후 RESTART 버튼을 통해 즉시 재시작이 가능하다.
  • 클라이언트 → RESTART
  • 서버 → game.reset() 호출
  • START → STATE → TURN 재전송
복잡한 투표 구조 없이,
테스트 및 반복 플레이에 최적화된 방식이다.

9. 결과 및 정리

이번 구현을 통해 다음을 명확히 경험할 수 있었다.
  • TCP 기반 양방향 통신 구조
  • 서버 권한 게임 설계의 중요성
  • Unity 메인 스레드 제약 대응 방식
  • 단순한 규칙의 게임도 구조가 핵심이라는 점

마무리

작은 게임이라도 통신 구조를 제대로 설계하면 학습 가치가 매우 크다.
이 틱택토 프로젝트는 TCP 기반 멀티플레이 구조를 이해하기 위한 훌륭한 출발점이다.
notion image
Share article