Amazon GameLift Realtime Server Workshop 진행 해보기- Part.2 실시간 서버 생성하기

An mihyang
Cloud Villains
Published in
13 min readJun 30, 2023

이전 포스트 사전 준비에 이어서 GameLift를 사용하여 실시간 서버를 생성해 보도록 하겠습니다.

워크샵의 출처는 아래와 같습니다.
https://catalog.us-east-1.prod.workshops.aws/workshops/bccf7c14-8f6f-441b-a4ff-fd6a2b402892/ja-JP/10-server

1. GameLift Realtime Server Script 개요

1.1. GameLift Realtime Server Script 추가

server.js 파일 생성 후에 아래 코드를 추가합니다.

다음 코드는 GameLift Realtime Server로 필수 기능이 정의되어 있습니다.

'use strict';

var session; // The Realtime server session object
var logger; // Log at appropriate level via .info(), .warn(), .error(), .debug()

// Called when game server is initialized, passed server's object of current session
function init(rtSession) {
session = rtSession;
logger = session.getLogger();
}

// On Process Started is called when the process has begun and we need to perform any
// bootstrapping. This is where the developer should insert any code to prepare
// the process to be able to host a game session, for example load some settings or set state
//
// Return true if the process has been appropriately prepared and it is okay to invoke the
// GameLift ProcessReady() call.
function onProcessStarted(args) {
return true;
}

// Called when a new game session is started on the process
function onStartGameSession(gameSession) {
// Complete any game session set-up
}

// Handle process termination if the process is being terminated by GameLift
// You do not need to call ProcessEnding here
function onProcessTerminate() {
// Perform any clean up
}

// On Player Connect is called when a player has passed initial validation
// Return true if player should connect, false to reject
function onPlayerConnect(connectMsg) {
return true;
}

// Called when a Player is accepted into the game
function onPlayerAccepted(player) {
}

// On Player Disconnect is called when a player has left or been forcibly terminated
// Is only called for players that actually connected to the server and not those rejected by validation
// This is called before the player is removed from the player list
function onPlayerDisconnect(peerId) {
}

// Return true if the player is allowed to join the group
function onPlayerJoinGroup(groupId, peerId) {
return true;
}

// Return true if the player is allowed to leave the group
function onPlayerLeaveGroup(groupId, peerId) {
return true;
}

// Return true if the send should be allowed
function onSendToPlayer(gameMessage) {
return true;
}

// Return true if the send to group should be allowed
// Use gameMessage.getPayloadAsText() to get the message contents
function onSendToGroup(gameMessage) {
return true;
}

// Handle a message to the server
function onMessage(gameMessage) {
}

// Return true if the process is healthy
function onHealthCheck() {
return true;
}

exports.ssExports = {
init: init,
onProcessStarted: onProcessStarted,
onStartGameSession: onStartGameSession,
onProcessTerminate: onProcessTerminate,
onPlayerConnect: onPlayerConnect,
onPlayerAccepted: onPlayerAccepted,
onPlayerDisconnect: onPlayerDisconnect,
onPlayerJoinGroup: onPlayerJoinGroup,
onPlayerLeaveGroup: onPlayerLeaveGroup,
onSendToPlayer: onSendToPlayer,
onSendToGroup: onSendToGroup,
onMessage: onMessage,
onHealthCheck: onHealthCheck
};

아무것도 넣지 않은 상태의 코드입니다.

이제 이 스크립트를 수정하여 퍼즐 게임 서버를 만들어 봅시다.

참고: https://docs.aws.amazon.com/ko_kr/gamelift/latest/developerguide/realtime-script-callbacks.html

2. GameLift Server 시작 흐름

2.1. GameLift Realtime Server 및 GameLift Service의 시작 흐름

Realtime Server를 시작하면 init과 onProcessStarted가 호출됩니다.

2.2. 로깅 기능 추가

그런 다음 서버 초기화 및 프로세스를 시작할 때 로그를 남기도록 코드를 추가하고 로그를 확인합니다.

'use strict';
const version = '0.1.0';
const util = require('util');

var session; // The Realtime server session object
var logger; // Log at appropriate level via .info(), .warn(), .error(), .debug()

// Called when game server is initialized, passed server's object of current session
function init(rtSession) {
session = rtSession;
logger = session.getLogger();
logger.info(`[init] version=${version}`);
}

function dump(obj, depth) {
return util.inspect(obj, {
showHidden: true,
depth: depth || 0
});
}

// On Process Started is called when the process has begun and we need to perform any
// bootstrapping. This is where the developer should insert any code to prepare
// the process to be able to host a game session, for example load some settings or set state
//
// Return true if the process has been appropriately prepared and it is okay to invoke the
// GameLift ProcessReady() call.
function onProcessStarted(args) {
logger.info(`[onProcessStarted] ${dump(args)}`);
return true;
}

3. GameLift Realtime Server Script 생성

3.1. GameLift에 업로드할 스크립트 준비

앞서 1.1 단계에서 생성한 server.js 파일을 zip으로 압축합니다.

폴더가 아닌 server.js 파일을 압축합니다.

  • MAC의 경우: 마우스 우클릭 후 server.js 압축을 선택합니다. 또는 CLI로도 압축이 가능합니다.
    zip server.js.zip server.js
  • Windows10의 경우: server.js 파일 우클릭 후 보내기 → 압축(zip 형식) 폴더 선택
  • Windows11의 경우: server.js 파일 우클릭 후 ZIP파일로 압축

3.2. GameLift에 스크립트 업로드

AWS Management Console에 로그인한 후 서비스 검색 필드에 GameLift를 입력한 다음 GameLift를 클릭합니다.

좌측 탐색 창에서 스크립트 → 스크립트 생성

스크립트 설정 후 생성합니다.

  • 이름: Puzzle
  • 버전: 0.1.0
  • 게임 서버 스크립트: zip 파일 업로드 선택 후 파일 선택 → 3.1 단계에서 생성한 zip 파일 선택

업로드 결과 확인

4. GameLift Fleet 만들기

Amazon GameLift 콘솔의 좌측 탐색 창에서 플릿을 선택한 후 플릿 생성 버튼을 클릭합니다.

컴퓨팅 유형으로 Managed EC2를 선택한 후 다음 단계로 넘어갑니다.

  • 플릿 이름 : PuzzleFleet
  • 바이너리 형식 : 스크립트
  • 스크립트 : 3.2 단계에서 생성한 스크립트 선택

나머지 설정은 그대로 두고 다음 단계로 이동합니다.

위치는 GameLift를 생성 중인 홈 리전으로 설정합니다.

비용 절감을 위해 스팟 인스턴스 선택 후 c5.large 유형을 선택합니다.

플릿을 생성하면 zip파일로 압축한 파일(server.js.zip)이 압축 해제되어 /local/game/ 아래에 위치하게 됩니다.

시작 경로에 위에서 생성한 파일명 server.js를 넣고 동시 프로세스는 10개로 띄웁니다.

태그 단계는 건너 뛴 후 설정이 완료 됐다면 검토 후에 제출 버튼을 클릭하여 플릿을 생성합니다.

생성된 플릿 선택 → 이벤트로 이동하여 플릿 초기화가 완료될 때까지 기다립니다.

참고: https://docs.aws.amazon.com/gamelift/latest/apireference/API_Event.html

초기화를 기다리는 동안 다음 단계로 이동하여 별칭을 생성합니다.

4.1. GameLift 별칭 만들기

Amazon GameLift 콘솔의 좌측 탐색 창에서 별칭 선택 후에 별칭 생성을 클릭하여 새로운 별칭을 생성합니다.

별칭 설정 후에 생성 버튼을 클릭하여 별칭을 생성합니다.

  • 이름: PuzzleAlias
  • 라우팅 유형: 단순
  • 플릿: 이전 단계에서 생성한 플릿 선택

별칭 생성이 정상적으로 되었는지 확인합니다.

그럼 다음 포스트에서 이어서 Puzzle Game을 만들어 보도록 하겠습니다.

--

--