오늘의 목표

더보기

✔️ 프로그래머스 코테 문제 풀이

✔️ TCP 서버 강의 완강

✔️ 개인 과제 프로젝트 시작

 


⏱️ 오늘의 일정

프로그래머스 코테 문제 풀이

 

TCP 서버 강의 완강

 

개인 과제 프로젝트 시작


📜 프로그래머스 코테 문제 풀이

 

개인 정보 수효 유집기간

https://github.com/YamSaeng/AlgorithmCodingTest/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/1/150370.%E2%80%85%EA%B0%9C%EC%9D%B8%EC%A0%95%EB%B3%B4%E2%80%85%EC%88%98%EC%A7%91%E2%80%85%EC%9C%A0%ED%9A%A8%EA%B8%B0%EA%B0%84

 

AlgorithmCodingTest/프로그래머스/1/150370. 개인정보 수집 유효기간 at main · YamSaeng/AlgorithmCodingTest

This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - YamSaeng/AlgorithmCodingTest

github.com

 

function solution(today, terms, privacies) {
    const answer = [];

    // 들어온 today를 Date형식으로 바꾼다
    const expireDay = new Date(today);

    const termArray = {};
    terms.forEach((item) => {
        // split() 메서드로 분리한 타입과 기간을
        // 구조 분해 할당으로 변수화 한다.
        const [type, term] = item.split(" ");

        // 타입에 기간이 얼만지 객체로 생성한다.    
        termArray[type] = Number(term);
    });

    // 개인정보 수집일자를 확인한다.
    privacies.forEach((item, index) => {
        // 위와 마찬가지로 구조 분해 할당을 한다.
        const [date, type] = item.split(" ");

        // 구한 date는 new Date() 메서드를 통해 Date 형식으로 변환한다.
        const newDate = new Date(date);

        // 그리고 Date의 매서드인 setMonth를 이용해
        // chDate의 현재 달 + 타입의 기간을 더한 값을 구한다.
        newDate.setMonth(newDate.getMonth() + termArray[type]);

        // 마지막으로 오늘 날짜와 구한 유효기간을 비교해
        // 유효기간이 오늘 보다 작거나 같으면 answer에 번호를 넣는다.
        if (newDate <= expireDay) {
            answer.push(index + 1);
        }
    });

    return answer;
}

 

 

📜 TCP 서버 강의 완강

 

캠프에서 제공해준 tcp 서버 강의를 완강했다.매우 많은 내용이 담겨 있었는데, 정리해보자면 다음과 같다.

 

웹소켓으로 서버를 열고 접속하는 것이 아닌 TCP로 서버를 열고 접속하는 방식,DB Connection Pool 생성, 서버와 클라가 주기적으로 주고 받는 핑퐁 패킷,프로토 버프, 레이턴시와 해결방법 등

 

DB Connection Pool은 이전 c++ 게임서버에서 만든 경험이 있어서 어떤 부분이 다른가를 기대하면서 봤는데,전체적인 방식은 똑같지만 아래 코드 처럼 mysql자체에서 pool을 호출해서 만든다는 점이 매우 흥미로웠다.

 const pool = mysql.createPool({
        host: dbConfig.host,
        port: dbConfig.port,
        user: dbConfig.user,
        password: dbConfig.password,
        database: dbConfig.name,
        // MAX 연결 값을 넘은 요청이 들어올 경우
        // 이미 요청 중인 대상의 작업이 끝날 때까지 대기한다는 의미
        waitForConnections: true,
        connectionLimit: 10, // 커넥션 풀에서 최대 연결 수
        // 대기할 때 몇개의 요청을 대기 시킬 것인지에 대한 값 ( 0일 경우 무제한 대기열 )                   
        // 예) 2일 경우 3부터 대기하는 대상에게는 에러를 반환
        queueLimit: 0, 
    });

 

 

핑퐁 패킷을 주고 받으면서 앞서 언급한 레이턴시를 측정하고, 해당 데이터를 통해 접속한 클라들의 레이턴시를 맞춰가면서 처리하는 부분이 매우 흥미로웠다.

 

아래 코드 처럼 핑 패킷을 보내고, 클라에서는 핑 패킷을 받으면 퐁 패킷을 보내고, 최종적으로 서버가 받아 퐁 패킷을 기록한다. 결국 핑을 보내고, 퐁을 받을 때의 시간차이를 기록해 해당 클라와의 레이턴시를 기록한다.

// 핑 패킷 보내기
ping() {
    const now = Date.now();
    
    this.socket.write(createPingPacket(now));
}

// 퐁 패킷 받기
handlePong(data) {
    const now = Date.now();
    // 왕복 값이므로 2로 나눠준다.
    this.latency = (now - data.timestamp) / 2;
}

 

 

📜 개인 과제 프로젝트 시작

 

TCP 강의를 완강하고, TS로 프로젝트를 만든 후 기본적인 서버를 열고, 클라로 접속하는 부분 까지 만들었다.

 

게임 서버 클래스 ( 게임 서버를 열고, 접속을 담당 한다 . )

import net from "net";
import { config } from "../config/Config.js";
import { OnData } from "../events/OnData.js";
import { OnEnd } from "../events/OnEnd.js";
import { OnError } from "../events/OnError.js";

class GameServer {
    public recvCount: number;
    public sendCount: number;
    private server: any;    

    constructor() {
        this.recvCount = 0;
        this.sendCount = 0;
        this.server = net.createServer(this.Accept);
    } 

    StartGameServer() {
        console.log("게임서버 시작");

        this.Listen();
    }

    Listen() {
        this.server.listen(config.gameserver.port, config.gameserver.host, () => {
            console.log(`서버가 ${config.gameserver.host}:${config.gameserver.port}에서 실행 중입니다.`);
            console.log(this.server.address());
        });
    }

    Accept(socket: any) {
        console.log("클라 접속", socket.remoteAddress, socket.remotePort);

        socket.on("data", OnData(socket));
        socket.on("end", OnEnd(socket));
        socket.on("error", OnError(socket));
    }
}

export default GameServer;

 

 

메인 ( 프로그램 진입점 )

import GameServer from "./server/Server.js";

const gameServer = new GameServer();

function Main() {
    gameServer.StartGameServer();    
}

Main();

 

클라이언트 ( 서버 접속 테스트 용 )

import { config } from "../config/Config.js";
import net from "net";

const client = new net.Socket();

client.connect(5555, config.gameserver.host, async () => {
   
});

client.on("close", () => {
    console.log("클라 소켓 종료");
});

 

클라이언트는 우선 간단하게 위처럼 만들었는데, 추후에 클래스로 다중 접속을 시도해볼 예정이다.

많은 더미를 생성해 내가 만든 서버를 테스트 해 볼 생각!

+ Recent posts