WebAPIGame

개요

  • Unity 엔진과 웹 통신을 같이 활용해 실제 서비스 가능한 게임을 만들어보는 연습을 하고자하는 프로젝트입니다.
  • 간단한게 웹로그인 + 채팅 + 간단한 미니 게임 시스템만 구현한 뒤 점차 시스템 추가해나가면서
    유지보수 할 수 있는 장기적인 프로젝트로 끌어가는게 목적입니다.
  • 이 포스트에서는 프로젝트 환경설정, 구조설계 및 배포까지만 수행한 뒤, 간단한 미니 게임(가위바위보)만 구현하는 정도로 정리합니다.
  • 2026/03에 시작해 학기 중(6월까지)에 어느정도 완성하는걸 목표로 하고있습니다.

구현 목표

  • 웹에서 회원가입 후, 유니티 클라이언트에서 로그인.
  • 친구기능. 길드 기능. 채팅 기능. 미니게임(가위바위보) 각종 게임 시스템 구현
  • 웹 사이트는 Next.js, 웹 서버는 asp.net 사용. 회원 정보는 SQLite에 저장

기술 스택

  • C#, ASP.Net Core, Next.js, gRPC, SQLite,

예상 프로젝트 구조

  • 게임 클라이언트(C# Console), 게임 웹 서버(ASP.Net Core), 로그인 및 대기열 서버(ASP.Net Core), 로그인 웹사이트(Next.js)
  • 4개 프로젝트를 합친 하나의 모노레포로 관리
  • 웹 사이트는 깃허브 페이지를 통해 배포, 웹 서버는 AWS를 통해 배포. 게임은 공식적인 배포 예정 없음

대략적인 프로젝트 동작 예상

  • 깃허브 페이지를 통해 배포된 웹 사이트를 이용해 회원가입
  • 게임 측에서 로그인 서버에 접속 및 로그인. 서버 목록 받고서 대기열 대기 후 게임 웹 서버 연결
  • 게임과 게임 서버 웹통신을 통한 멀티플레이

깃허브 저장소

웹사이트

목차

  1. ASP.Net Core, API 서버 프로젝트 생성
  2. Next.js 프로젝트 생성 및 fetch를 통한 동적 사이트 구현
  3. Next.js 웹사이트 github pages를 통한 배포 및 웹 서버 AWS 배포
  4. 게임 서버(ASP.Net) 프로젝트 생성 및 AWS 배포
  5. 유니티 프로젝트 생성 및 웹 로그인, 게임 서버 연결 확인
  6. 게임 컨텐츠 개발(가위바위보)

1. 로그인 서버(ASP.Net Core) 구성

  • todo
  1. api 구현 (Home(일반 테스트용), Auth(회원가입, 로그인 처리), User(인증된 유저 요청 처리), health(서버 체크))
  2. DB 연결 -> SQLite. 회원 정보 저장
  3. API 테스트(Swagger)

1-1. ASP.Net 프로젝트 초기 설정

  • API 웹 서버를 만들기 위한 프로젝트 초기 설정을 수행합니다.

ASP.NET Core 빈 프로젝트를 생성

asp.net 프로젝트 생성

Nuget 패키지 설치

  • 프로젝트에서 사용할 패키지들을 설치합니다.
cmd
dotnet add package Microsoft.IdentityModel.JsonWebTokens
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Swashbuckle.AspNetCore
  • JsonWebTokens: JWT 생성용
  • JwtBearer: 웹 요청 JWT 인증용
  • Sqlite: SQLite 사용하기 위한 패키지
  • Swashbuckle: Swagger를 통한 API 테스트용 패키지

Program.cs

Program.cs
c#
Program.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using WebServer.Data;
 
namespace WebServer
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            
            // API 컨트롤러 사용 설정
            builder.Services.AddControllers();
 
            // cors 제외 설정
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowFrontend", policy =>
                    policy.WithOrigins(
                        "https://crusthack.github.io",
                        "http://localhost:3000"
                        )
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                    );
            });
 
            // JWT 인증 설정
            var jwtKey = builder.Configuration["Jwt:Key"] ?? "change_this_to_a_secure_long_key";
            var keyBytes = Encoding.UTF8.GetBytes(jwtKey);
 
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
                    ValidateLifetime = true
                };
            });
            builder.Services.AddAuthorization();
 
 
            // 5. EF Core DbContext 등록 (SQLite 사용)
            builder.Services.AddDbContext<AppDbContext>(options =>
                options.UseSqlite(builder.Configuration.GetConnectionString("app")));
 
            // 6. Swagger 등록
            if (builder.Environment.IsDevelopment())
            {
                // 개발 환경일 때만 API 명세 서비스를 준비합니다.
                builder.Services.AddEndpointsApiExplorer();
                builder.Services.AddSwaggerGen();
            }
 
 
            // 앱 설정 
            var app = builder.Build();
 
            // HTTP요청 HTTPS로 리다이렉션
            app.UseHttpsRedirection();
 
            // db 설정
            using (var scope = app.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context = services.GetRequiredService<AppDbContext>();
 
                // 테이블이 없으면 생성
                context.Database.EnsureCreated();
            }
 
            // 개발 환경 체크
            if (app.Environment.IsDevelopment())
            {
                // swagger 사용 설정 
                app.UseSwagger();
                app.UseSwaggerUI();
            }
 
            // cors 설정 
            app.UseCors("AllowFrontend");
 
            // 인증/인가 미들웨어
            app.UseAuthentication();
            app.UseAuthorization();
 
            // 컨트롤러 매핑 
            app.MapControllers();
 
            app.Run();
        }
    }
}

API 컨트롤러 추가(HomeController)

  • 웹 요청을 처리하는 API 컨트롤러를 추가합니다.
Controllers/HomeController.cs
c#
Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
 
namespace WebServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        public class TestRequest
        {
            public required string testMessage { get; set; }
            public required int testNumber { get; set; }
        }
 
        // /로 시작하면 절대 경로 지정임. 
        [HttpGet("/")]
        public string Index()
        {
            return "hello, world!!!";
        }
 
        [HttpPost("test")]
        public string Test(TestRequest request)
        {
            return $"test message: {request.testMessage}. testNum: {request.testNumber}";
        }
    }
}

Swagger을 통한 API 테스트

  • /swagger 주소로 접근하면 서버에 연결된 API 목록이 보이고, 각 API를 클릭하면 요청을 보낼 수 있는 인터페이스가 나타납니다. Swagger UI

1-2. SQLite 회원가입 및 JWT를 통한 로그인 인증 처리.

  • todo
  1. SQLite DB 연결 및 스키마 생성, 회원가입 처리
  2. 로그인시 JWT 발급. JWT를 통한 인증 처리.

1. 회원정보를 저장할 DB의 User 스키마 정의

  • 저장할 회원 정보
  1. UserNo 회원 번호. 메인 키이며 Identity하게 1씩 증가
  2. UserID 회원 아이디. Unique한 string
  3. PasswordHash 해시된 Password 값
  4. PasswordSalt 유저마다 가지는 고유한 비밀번호 salt값
  5. CreatedAt 계정 생성일

User 클래스

Models/User.cs
c#
Models/User.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
namespace WebServer.Models
{
    public class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserNo { get; set; }
        public required string UserID { get; set; }
 
        public required byte[] PasswordHash { get; set; }
        public required byte[] PasswordSalt { get; set; }
 
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
    }
}

SQLite DB Context

  • Program.cs에서 DB 연결 처리 되어있음. appsettings.json에 있는 SQLite 파일명 사용
Data/AppDbContext.cs
c#
Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using WebServer.Models;
 
namespace WebServer.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }
 
        public DbSet<User> Users { get; set; }
 
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        //  UserID에 인덱스 추가. 유니크 속성 부여
            modelBuilder.Entity<User>()
                .HasIndex(u => u.UserID)
                .IsUnique();
        }
    }
}

AuthController 회원가입 처리

Controllers/AuthController.cs
c#
Controllers/AuthController.cs
public class SignupRequest
{
    public string? UserID { get; set; }
    public string? Password { get; set; }
    public string? PasswordConfirm { get; set; }
}
 
[HttpPost("signup")]
public IActionResult Signup(SignupRequest request)
{
    if (request == null || string.IsNullOrWhiteSpace(request.UserID) || string.IsNullOrEmpty(request.Password))
        return BadRequest("Invalid signup request");
 
    if (request.Password != request.PasswordConfirm)
        return BadRequest("Passwords do not match");
 
    // for Test api
    {
        if (request.UserID == "string")
        {
            return Ok("signup api running well");
        }
 
        if (!TestCode(request))
        {
            return BadRequest("Please use test credentials starting with 'test' for UserID and 'qwer' for Password");
        }
    }
 
    // check existing user
    if (_context.Users.Any(u => u.UserID == request.UserID))
        return Conflict("Username already exists");
 
    CreatePasswordHash(request.Password, out var hash, out var salt);
 
    var user = new User
    {
        UserID = request.UserID,
        PasswordHash = hash,
        PasswordSalt = salt
    };
 
    _context.Users.Add(user);
    _context.SaveChanges();
 
    return Ok(new { message = "Signup successful" });
}
 
bool TestCode(SignupRequest request)
{
    if (!request.UserID!.StartsWith("test"))
    {
        return false;
    }
    if (!request.Password!.StartsWith("qwer"))
    {
        return false;
    }
 
    return true;
}

코드 설명

  • 유저 아이디와 비밀번호, 비밀번호 확인 값을 받고서 회원가입 처리를 합니다.
  • 현재 테스트 단계이므로 아이디는 test로 시작하는 값만, 비밀번호를 qwer로 시작하는 값만 받게 했습니다.
  • 아이디 중복 확인 후, 비밀번호 솔트와 해시값 만들고서 DB에 추가합니다.

2. 로그인 요청에 따른 JWT 발급 처리

  • 로그인 절차
  1. UserID 기반으로 DB에서 User탐색. null일 시 거부
  2. password기반으로 User의 salt와 hash값 가지고서 일치 확인
  3. UserNo와 UserID 정보를 가진 JWT 발급

Login 처리 코드

c#
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
    if (request == null || string.IsNullOrWhiteSpace(request.UserID) || string.IsNullOrEmpty(request.Password))
        return BadRequest("Invalid login request");
 
    var user = _context.Users.SingleOrDefault(u => u.UserID == request.UserID);
    if (user == null)
        return Unauthorized("Invalid username or password");
 
    if (!VerifyPassword(request.Password, user.PasswordHash, user.PasswordSalt))
        return Unauthorized("Invalid username or password");
 
    // Create JWT token
    var claims = new[] {
        new Claim(ClaimTypes.NameIdentifier, user.UserNo.ToString()),
        new Claim(ClaimTypes.Name, user.UserID)
    };  
 
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtKey));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
 
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = creds
    };
 
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
 
    return Ok(new { token = tokenString, userID = user.UserID });
}

최종 웹서버 api

  1. /api/Auth/signup: 회원가입
  2. /api/Auth/login: 로그인
  3. /api/User/info: 로그인된 사용자가 JWT를 쿠키에 넣어 요청시, 해당 유저 정보 반환
  4. /api/User/everyuser: 테스트용으로, 가입된 모든 사용자들 정보 반환. (비밀번호 제외)
  5. /api/health: 서버 상태 반환
  6. /: hello, world!!! 반환

정리

  • Swagger를 통한 API 테스트가 가능한 상태이며, SQLIte 연결을 통해 회원 정보를 저장하였고. JWT를 발급해 로그인 및 인증 처리를 수행하는 웹 API 서버가 제작되었습니다.

2. 회원가입 웹사이트(Next.js) 제작

  • 웹사이트는 단순히 회원가입, 로그인 및 간단한 API 동작 테스트용도라서 크게 공들이진 않았습니다.
  • html요소 대부분 gemini cli을 사용하여 구현하였습니다.
  • 깃허브 페이지를 통해 배포하는 정적 호스팅 환경입니다.
  • fetch를 통한 클라이언트 사이드 렌더링의 동적 페이지를 제작합니다.

사진

사진 사진 사진 사진

lib/api.ts

  • API 요청 보내는 코드들, 한 곳에 다 모아둡니다.
  • api 주소는 수동으로 주석 처리하면서 개발 환경에 따라 바꿉니다.
lib/api.ts
ts
lib/api.ts
// API 설정
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL
// npm run dev로 실행시 로컬 웹서버 주소 사용 http://localhost:5001/api
// npm run dev2 및 production 환경에서는 crusthack.com/api의 배포된 웹 서버 사용 
 
 
interface SignUpData {
  userID: string;
  password: string;
  passwordConfirm: string;
}
 
interface LoginData {
  userID: string;
  password: string;
}
 
interface LoginResponse {
  token: string;
  userID: string;
}
// ...
 
// 공통 API 요청 함수
async function apiRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`;
  const headers = {
    "Content-Type": "application/json",
    ...(options.headers || {}),
  };
 
  const response = await fetch(url, { ...options, headers });
 
  if (!response.ok) {
    let errorDetail = "";
    try {
      // 본문을 텍스트로 먼저 읽어 스트림 소비 문제 방지
      const text = await response.text();
      try {
        // 텍스트를 JSON으로 파싱 시도
        const json = JSON.parse(text);
        errorDetail = typeof json === "string" ? json : JSON.stringify(json, null, 2);
      } catch {
        // JSON 파싱 실패 시 원본 텍스트 사용
        errorDetail = text;
      }
    } catch (e) {
      errorDetail = `에러 응답을 읽는 중 오류가 발생했습니다: ${response.statusText}`;
    }
    
    // 401 응답 시 전역 이벤트를 발생시켜 로그아웃 유도
    if (response.status === 401 && typeof window !== "undefined") {
      window.dispatchEvent(new Event("auth:unauthorized"));
    }
  }
 
  return response.json();
}
 
// 회원가입
export async function signUp(data: SignUpData): Promise<LoginResponse> {
  return apiRequest<LoginResponse>("/Auth/signup", {
    method: "POST",
    body: JSON.stringify(data),
  });
}
 
// 로그인
export async function login(data: LoginData): Promise<LoginResponse> {
  return apiRequest<LoginResponse>("/Auth/login", {
    method: "POST",
    body: JSON.stringify(data),
  });
}
 
// 사용자 정보 조회
export async function getUserInfo(token: string): Promise<UserInfoResponse> {
  return apiRequest<UserInfoResponse>("/user/info", {
    method: "GET",
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
}
// 이하 생략

로그인 jwt 쿠키 관리 lib/cookies.ts

  • 로그인 API 요청 응답으로 온 jwt 키를 쿠키에 저장하는 함수
  • 기존 브라우저에 저장된 쿠키로부터 jwt 가져오는 함수
  • jwt 쿠키 날려버리는 함수 셋이 있습니다.
ts
"use client";
 
const JWT_COOKIE_NAME = "auth_token";
const EXPIRY_DAYS = 7;
 
// JWT 토큰을 쿠키에 저장
export function setJWTCookie(token: string, expiryDays: number = EXPIRY_DAYS) {
  const expiryDate = new Date();
  expiryDate.setDate(expiryDate.getDate() + expiryDays);
 
  document.cookie = `${JWT_COOKIE_NAME}=${token};path=/;expires=${expiryDate.toUTCString()};SameSite=Strict`;
}
 
// 쿠키에서 JWT 토큰 가져오기
export function getJWTCookie(): string | null {
  const cookies = document.cookie.split(";");
  for (const cookie of cookies) {
    const [name, value] = cookie.trim().split("=");
    if (name === JWT_COOKIE_NAME) {
      return value || null;
    }
  }
  return null;
}
 
// JWT 토큰 삭제 (로그아웃)
export function removeJWTCookie() {
  document.cookie = `${JWT_COOKIE_NAME}=; path=/; max-age=0; SameSite=Strict`;
}

브라우저 로그인 컨텍스트

ts
"use client";
 
import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from "react";
import { getJWTCookie, setJWTCookie, removeJWTCookie } from "./cookies";
import { getUserInfo, UserInfoResponse } from "./api";
 
interface AuthContextType {
  user: UserInfoResponse | null;
  token: string | null;
  isLoading: boolean;
  isLoggedIn: boolean;
  setToken: (token: string | null) => void;
  refreshUserInfo: () => Promise<void>;
  logout: () => void;
}
 
const AuthContext = createContext<AuthContextType | undefined>(undefined);
 
export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<UserInfoResponse | null>(null);
  const [token, setTokenState] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
 
  const logout = useCallback(() => {
    setUser(null);
    setTokenState(null);
    removeJWTCookie();
  }, []);
 
  // API 401 에러 감지 시 자동 로그아웃 처리
  useEffect(() => {
    const handleUnauthorized = () => {
      console.warn("인증이 만료되었습니다. 로그아웃 처리합니다.");
      logout();
    };
 
    window.addEventListener("auth:unauthorized", handleUnauthorized);
    return () => window.removeEventListener("auth:unauthorized", handleUnauthorized);
  }, [logout]);
 
  const fetchUserInfo = useCallback(async (authToken: string) => {
    try {
      const info = await getUserInfo(authToken);
      setUser(info);
    } catch (error) {
      console.error("사용자 정보 조회 실패:", error);
    }
  }, []);
 
  // 초기 로딩 시 쿠키에서 토큰 확인 및 유저 정보 조회
  useEffect(() => {
    const initAuth = async () => {
      const savedToken = getJWTCookie();
      if (savedToken) {
        setTokenState(savedToken);
        await fetchUserInfo(savedToken);
      }
      setIsLoading(false);
    };
    initAuth();
  }, [fetchUserInfo]);
 
  const setToken = async (newToken: string | null) => {
    setTokenState(newToken);
    if (newToken) {
      setJWTCookie(newToken);
      await fetchUserInfo(newToken);
    } else {
      removeJWTCookie();
      setUser(null);
    }
  };
 
  const refreshUserInfo = async () => {
    if (token) {
      await fetchUserInfo(token);
    }
  };
 
  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        isLoading,
        isLoggedIn: !!token,
        setToken,
        refreshUserInfo,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}
 
export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within AuthProvider");
  }
  return context;
}

3. 웹사이트 및 웹 서버 배포

  • 지금까지 Next.js 웹사이트 배포 시에, Next.js 프로젝트를 루트폴더로 사용하여 Github에서 제공하는 yml을 통해 자동으로 배포했었습니다.
  • 여러개 프로젝트 폴더를 모아서 하나의 레포로 관리하기 때문에 github action 동작을 이해하고 yml을 수정해야 합니다.
  • AWS를 통한 ASP.Net 웹서버 배포시, 인스턴스에 레포지토리로부터 웹 서버 하나만 다운받는 법을 배워야 합니다.
  • 일단은 서버가 적기 때문에 매번 직접 클라우드에 접속하여 배포를 수행하여도 되지만, yml을 통해 aws 클라우드 자동 배포하는 법을 배워야합니다.

Next.js 깃허브 페이지를 통한 배포

yml
name: Deploy Next.js site to Pages
 
    # yml, Github Action 자동 실행 조건. 
on:
  push:
    branches: ["main"]
    # website 폴더 내의 변경사항이 있을 때만 실행
    paths:
      - 'website/**'
 
  workflow_dispatch:
 
permissions:
  contents: read
  pages: write
  id-token: write
 
concurrency:
  group: "pages"
  cancel-in-progress: false
 
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
 
      - name: Detect package manager
        id: detect-package-manager
        # working-directory로 website 폴더 사용 설정
        working-directory: ./website
        run: |
          if [ -f "yarn.lock" ]; then
            echo "manager=yarn" >> $GITHUB_OUTPUT
            echo "command=install" >> $GITHUB_OUTPUT
            echo "runner=yarn" >> $GITHUB_OUTPUT
            exit 0
          elif [ -f "package.json" ]; then
            echo "manager=npm" >> $GITHUB_OUTPUT
            echo "command=ci" >> $GITHUB_OUTPUT
            echo "runner=npx --no-install" >> $GITHUB_OUTPUT
            exit 0
          else
            echo "Unable to determine package manager"
            exit 1
          fi
 
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: ${{ steps.detect-package-manager.outputs.manager }}
          # 캐시 lock 파일 위치 명시
          cache-dependency-path: ./website/package-lock.json
 
      - name: Setup Pages
        uses: actions/configure-pages@v5
        with:
          static_site_generator: next
 
      - name: Restore cache
        uses: actions/cache@v4
        with:
          path: |
            ./website/.next/cache
          key: ${{ runner.os }}-nextjs-${{ hashFiles('website/**/package-lock.json', 'website/**/yarn.lock') }}-${{ hashFiles('website/**/*.[jt]s', 'website/**/*.[jt]sx') }}
          restore-keys: |
            ${{ runner.os }}-nextjs-${{ hashFiles('website/**/package-lock.json', 'website/**/yarn.lock') }}-
 
      - name: Install dependencies
        working-directory: ./website
        run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }}
 
      - name: Build with Next.js
        working-directory: ./website
        run: ${{ steps.detect-package-manager.outputs.runner }} next build
 
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./website/out
 
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

next.js 배포 yml 절차 이해

  1. on: 깃허브 액션 실행 조건. website 폴더에 푸쉬 사항이 있을 때 실행
  2. jobs: 작업 단위 동작 구분
  3. build: 빌드 작업. 깃허브가 제공하는 가상환경에서 빌드 수행.
  4. step, name: 스탭 단위로 동작 구분. 실질적으로 논리 돌리는 부분. name으로 스탭 이름단위 구분
  5. uses: 깃허브 측에서 이미 만들어둔 동작(함수나 명령어처럼 생각)을 수행
  6. run: 쉘 명령어 실행 부분.
  7. 나머지는 알아서 해석. ./website라고 경로 지정해줌으로써 Next.js 프로젝트 깃허브 액션을 통해 배포 수행

AWS에 웹서버 자동 배포

  • 현재 AWS에 EC2 인스턴스 생성 후 pem을 발급 받았으며,
    Claudflare에 도메인 구입을 통해 crusthack.com을 통한 접속이 가능한 상태입니다.
  • ssh -i *.pem username@crusthack.com 으로 접근 가능
  • 해야할 일:
  1. yml 작성을 통한 깃허브 액션 추가. 깃허브 액션을 통해 쉘 접속 및 클라우드에서 서버 실행
  2. ssl 인증서 발급을 통해 https 옵션 켜기. 자동 재발급 시스템 구현

웹서버 aws 배포 자동화

  1. 깃허브 레포지토리 세팅에 들어가서 secrets and variables의 Action 탭 진입.
  2. Repository secrets에 EC2_SSH_KEY_WEB_SERVER(pem 내용), EC2_USERNAME, EC2_HOST, CERT_PASSWORD 추가
  3. 위의 비밀 값들을 이용한 yml 스크립트 작성
  • yml 내용: .Net 빌드, 빌드 결과물 aws에 scp로 전송(덮어쓰기), 쉘 접속 후 기존 서버 프로세스 킬 및 서버 구동
  • SSL인증서는 Certbot을 통해 발급 받음.

웹 서버 배포 yml 스크립트

.github/workflows
yml
.github/workflows
name: ASP.Net Login Web Server AWS Deploy
 
on:
  push:
    branches: [ "main" ]
    paths:
      - 'WebServer/**' # 웹 서버 코드가 수정될 때만 배포 실행
 
jobs:
  deploy:
    runs-on: ubuntu-latest
 
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
 
      # 1. .NET 빌드 (ASP.NET Core 프로젝트 기준)
      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0'
 
      - name: Build and Publish
        run: |
          dotnet publish WebServer/WebServer.csproj -c Release -o ./publish
 
      # 2. 빌드된 파일을 AWS로 전송 (SCP)
      - name: Copy files to AWS
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_SSH_KEY_WEB_SERVER }}
          source: "./publish/*"
          target: "/home/${{ secrets.EC2_USERNAME }}/game-server"
          strip_components: 1
 
      # 3. 서버에서 기존 프로세스 종료 후 재실행 (SSH)
      - name: Restart Server
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_SSH_KEY_WEB_SERVER }}
          script: |
            # 기존 포트(5000)를 사용하는 프로세스 종료
            sudo fuser -k 5000/tcp || true
            cd /home/${{ secrets.EC2_USERNAME }}/game-server
            chmod +x WebServer
            # 환경 변수와 함께 실행 (Kestrel 설정 덮어쓰기)
            # 이름 규칙: 설정명__하위설정명__속성명
            export Kestrel__Endpoints__Https__Certificate__Password="${{ secrets.CERT_PASSWORD }}"
            # 백그라운드 실행
            nohup ./WebServer > server.log 2>&1 &

SSL 인증서 자동 업데이트

  • SLL을 통해 발급받은 인증서는, 90일마다 만료된다고 함.
  • 이를 위해 자동으로 재발급 해주는 쉘을 작성해 백그라운드에서 돌리면 됨.
  • 귀찮아서 생략

중간 점검(2026/05/02)

  • Next.js로 만든 웹사이트를 깃허브 페이지에 배포하였음.
  • 웹 api서버를 통해 회원가입, 로그인, 회원 정보 조회, 모든 사용자 정보 조회 가능
  • ASP.Net Core 웹 API 서버를 깃허브 액션을 통해 AWS 배포하는것을 자동화 완료하였음
  • 해당 웹서버는 AWS에서 elastic ip를 통해 고정하였고, cloudflare에서 도메인을 구매하여 crusthack.com으로 고정하였음
  • 아직 각 프레임워크에서 개발환경/배포환경 구분하는게 미숙함

todo

  • 유니티에서 웹 서버 로그인 확인
  • 게임 웹 서버 구현 및 배포
  • 게임 서버 목록 및 대기열 시스템 구현
  • 유니티에서 웹 서버 로그인 - 게임 웹 서버 접속 확인

게임 서버 전략 세우기

  • 게임 서버 요구 사항
  1. 각 유저별 데이터 저장 -> 데이터베이스 요구
  2. 서로 다른 서버 - 데이터 독립적. 각 서버별 식별 필요
  3. 로그인서버와 통신을 통해 대기열 관리 해야 함

게임 서버 시나리오

  • 게임 서버 2개 배포(A, B 서버)예정
  • B 서버는 최대 수용 인원 1명으로 설정해 대기열 테스트용 서버로 사용, 실질적 멀티플레이는 A에서만 수행
  • 하나의 프로젝트를 똑같이 빌드하고서 실행한 뒤 서로 다른 컨텍스트를 가져야함
  • 컨텍스트 주입 방법 1. 실행된 게임 서버가 웹서버에 자신의 컨텍스트를 요청해서 받아옴. 혹은 실행하는 과정에서 주입
  • config 파일 수동으로 넣고서 서버 실행 혹은 쉘 스크립트를 통해 자동화 가능?
  • 일단 내 수준에선 config 파일 수동으로 집어넣고서 실행할 때 옵션 넣는게 좋을 듯

4. 게임 서버 구현

  • 기본 동작: 유저가 게임 서버에 접속한 후, gRPC 및 http를 통한 멀티 플레이 제공
  • 서버 접속 시나리오: 게임 서버가 실행된 후, 로그인 서버에 자신의 정보(서버 이름, 포트번호, 최대 접속가능 수, 현재 접속인원)를 알림.
    접속 인원이 변경될 때마다 지속적으로 post 실행.
  • 로그인 서버 - 게임 서버간의 통신에는 비밀 키값을 사용해 인증을 수행함. (횐경변수 "Custom:SecretKey")
  • 로그인 서버와 같은 AWS EC2 인스턴스에 올림. 포트번호는 5000, 7000 이런 식으로

네트워크 IP 관련

  • 서버 실행시 0.0.0.0, 전체 주소로 실행. 게임 서버는 자신의 공인 IP를 자동으로 알아낼 방법이 있는가?
  • 다른 호스트에 웹통신을 보낸뒤, 해당 호스트가 관찰한 뒤 전해준 자신의 IP를 공인 IP라고 생각할 수 있는가?
  • 일단 같은 ec2 인스턴스의 로그인 서버에 웹 요청을 보내므로, crusthack.com으로 요청 보낸 후 로그인 서버에서 보이는 ip번호를 확인함.(127.0.0.1로 뜸)
  • 일단은 로그인 서버 측에서 로컬호스트로 온 요청은 crusthack.com으로 대체하도록 시킴
  • 포트번호는 따로 로그인 서버로 알려야 됨.

GameServerContext.cs

  • 로그인 서버에 자신의 상태를 전달하기 위한 httpclient사용하는 싱글톤 클래스입니다.
  • 헤더에 "X-Secret-Key" 값을 넣어 서로 인증처리를 수행합니다.
GameServerContext.cs
cs
GameServerContext.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
 
namespace GameServer
{
    // 로그인 서버에 서버 정보 알리기 위한 클래스 
    public class GameServerContext
    {
        static private GameServerContext? _instance;
 
        private readonly string _serverName;
        private readonly int _serverCapacity;
        private readonly int _serverPort;
 
        private readonly string _loginURL;
        private readonly HttpClient _client;
 
        private readonly string _secretKey;
 
        public int CurrentConnectionCount { get; set; }
 
 
        private GameServerContext(IConfiguration configuration)
        {
            _serverName = configuration["Custom:ServerName"] ?? "";
            _serverCapacity = Int32.Parse(configuration["Custom:ServerCapacity"] ?? "0");
            var loginUrl = configuration["Custom:LoginServerURL"] ?? "";
            var secretKey = configuration["Custom:SecretKey"] ?? "";
 
            string fullAddress = configuration["Kestrel:Endpoints:Https:Url"] ?? "";
            var uri = new Uri(fullAddress);
 
            this._serverPort = uri.Port;
 
            _client = new HttpClient();
 
            if (string.IsNullOrEmpty(_serverName))
            {
                Console.WriteLine("Server Name is empty");
                throw (new Exception("Please input server name"));
            }
 
            CurrentConnectionCount = 0;
 
 
            _loginURL = loginUrl;
            _client = new HttpClient();
 
            _secretKey = secretKey;
        }
 
        static public GameServerContext Init(IConfiguration configuration)
        {
            _instance = new GameServerContext(configuration);
            _instance.Test();
            SendServerStatus();
 
            return _instance;
        }
 
        private void Test()
        {
            if (_instance == null) return;
 
            var req = new HttpRequestMessage(HttpMethod.Get, _loginURL);
            req.Headers.Add("X-Secret-Key", _secretKey);
 
            _ = _instance.SendRequest(req);
        }
 
        public class StatusData
        {
            public required string ServerName { get; set; }
            public required int PortNum { get; set; }
            public required int ServerCapacity { get; set; }
            public required int CurrentConnections { get; set; }
        }
 
        public static void SendServerStatus()
        {
            if (_instance == null) return;
 
            var req = new HttpRequestMessage(HttpMethod.Post, _instance._loginURL + "/api/gameserver/status");
            req.Headers.Add("X-Secret-Key", _instance._secretKey);
                
            var data = new StatusData                       
            {
                ServerName = _instance._serverName,
                PortNum = _instance._serverPort,
                ServerCapacity = _instance._serverCapacity,
                CurrentConnections = _instance.CurrentConnectionCount
            };
 
            req.Content = JsonContent.Create(data);
 
            _ = _instance.SendRequest(req);
            Console.WriteLine("Status message sent successfully.");
        }
 
 
        private async Task SendRequest(HttpRequestMessage request)
        {
            try
            {
                var res = await _client.SendAsync(request);
                if (res.IsSuccessStatusCode)
                {
                    Console.WriteLine("Message sent successfully.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending message: {ex.Message}");
            }
        }
    }
}

Main.cs

  • 서버가 실행될 때 GameServerContext를 통해 로그인서버에 상태 전달을 수행해야 함.
  • 서버가 온전히 실행되고서 해당 동작을 수행해야 하므로, 중간에 ApplicationStarted를 통해 동작을 등록
Main.cs
cs
Main.cs
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
 
    builder.Services.AddControllers();
 
    var serverName = builder.Configuration["Custom:ServerName"];
    var serverCapa = builder.Configuration["Custom:ServerCapacity"];
    Console.WriteLine($"Server Name: {serverName}");
    Console.WriteLine($"Server Capacity: {serverCapa}");
    Console.WriteLine($"Login Server Address: {builder.Configuration["Custom:LoginServerURL"]}");
 
    var app = builder.Build();
 
    // 서버 완전히 실행된 후 동작 
    app.Lifetime.ApplicationStarted.Register(() =>
    {
        GameServerContext.Init(builder.Configuration);
    });
 
    app.UseHttpsRedirection();
 
    app.UseAuthorization();
    app.MapControllers();
 
    app.Run();
}

HomeController

  • 기본 홈 컨트롤러
  • status api를 통해 로그인 서버가 게임서버 생존 확인
  • IsAuthorized를 통해 비밀키 인증
cs
[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
    private string _secretKey;
 
    public HomeController(IConfiguration configuration)
    {
        _secretKey = configuration.GetValue<string>("Custom:SecretKey") ?? "DefaultKey";
    }
    [HttpGet("/")]
    public IActionResult Index()
    {
        return Ok("hello, world!!");
    }
 
    [HttpGet("status")]
    public IActionResult Status()
    {
        if(!IsAuthorized())
        {
            return BadRequest();
        }
        Console.WriteLine("Login Server checked me");
 
 
        return Ok("Game Server running well");
    }
 
    private bool IsAuthorized()
    {
        return Request.Headers["X-Secret-Key"] == _secretKey;
    }
}

서버 구조 및 배포 과정 정리

  • 기존 로그인 서버 배포 yml에 게임 서버 배포를 추가하였음. 로그인 서버 - 게임 서버 배포가 순차적으로 이뤄짐
  • 게임 서버는 2개 인스턴스가 실행됨. (Server_A 이름의 최대 동접 100 서버, Server_B 이름의 최대동접 1 서버)
  • 서버가 실행될 때 한 번, 로그인 서버로 자신의 정보를 전달하면서 자신을 등록함. 서로 순차적으로 엉켜있음.
  • 주기적인 상태 전달을 하도록 수정해 서로간의 종속성을 제거할 필요가 있음.
  • 로그인 서버는 게임 서버 리스트 get 요청시, 현재 존재하는 게임 서버들의 상태를 확인하는 api를 통해 생존을 확인함.

웹사이트를 통해 확인한 게임 서버 리스트

이미지

5. 클라이언트 제작 및 웹 서버 통신 확인

todo 콘솔 클라이언트 제작, 로그인 및 게임 서버 접속 확인 및 gRPC 연결 간단한 가위바위보 게임 제작, 랭킹 시스템 유니티에 이식 5월 안에 완성하고서, 6월동안 그동안 한 포트폴리오 기술들 하나씩 정리

  • http 지연 응답에 대해

C# 콘솔 클라이언트

  • 콘솔 프로그램을 통해 우선적으로 웹통신 동작 확인과 로그인 서버 - 게임 서버 라우팅 동작을 구현 및 확인합니다.
  • 추후 서버 부하 테스트를 편하게 하기 위해서도 콘솔 프로그램 제작이 요구됩니다.

Http 통신(UnityWebRequest)

UnityWebRequest 클래스

  • UnityWebRequest.Get, UnityWebRequest.Post 와 같은 정적 메소드를 통해 webrequest 인스턴스 생성, 혹은 직접 new를 통해 생성 후 method 지정 가능
  • get/post 메소드 지정과 함께 url 지정, 데이터 지정하는 형식으로 사용.

사용 예시 코드

csharp
IEnumerator GetRequest(string uri)
{
    using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
    {
        webRequest.timeout = 5;
 
        yield return webRequest.SendWebRequest();
 
        if (webRequest.result == UnityWebRequest.Result.Success)
            Debug.Log("Received: " + webRequest.downloadHandler.text);
        else if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
                            webRequest.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.LogError("Error: " + webRequest.error);
        }
    }
}
 
IEnumerator PostRequest(string url, string json)
{
    using (UnityWebRequest webRequest = UnityWebRequest.Post(url, json, "application/json"))
    {
        // 타임아웃 추가
        webRequest.timeout = 5;
 
        yield return webRequest.SendWebRequest();
 
        if (webRequest.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Post 성공: " + webRequest.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Post 실패: " + webRequest.error);
        }
    }
}

쿠키(헤더) 설정

  • SetRequestHeader 메서드를 통해 설정.

gRPC

ASP.Net Core 서버에 gRPC 서비스 추가

  • dotnet add package Grpc.AspNetCore
  1. 게임 방 생성(최대 2인임) -> 상대방 게임 방 리스트 조회 후 참여 -> 게임 시작 요청, 게임 생성 및 진행
  2. 매칭 돌리기 자동으로 게임 참여 처리 -> 게임 진행
  • 30초 하트비트 형식으로 클라이언트 세션 유지 처리

6. 클라이언트 게임 구현

기획

  • 구현하고 싶은 것
  1. 대기열 서버, 채팅, 길드, 친구 시스템.
  2. mmorpg -> 캐릭터, 몬스터 동기화 및 인벤토리 시스템
  3. 매치메이킹 시스템. 랭킹, mmr 구현. 가위바위보 같은 미니 게임으로
    => 3D 게임. 마을에서는 사이드 뷰, 필드에서는 탑뷰 방식.
  • 이번에는 대기열 서버와 가위바위보 게임과 매치메이킹 및 랭킹 시스템만 구현.
  • 방학 이후 여타 시스템 개발

게임 서버 유저 정보 시스템

가위바위보 게임 구현

대기열 시스템