TIL

[240709 TIL] 게임 서버 주특기 플러스 개인 과제 정리

jeongmin02 2024. 7. 9. 17:41

 

클라에서 서버로 들어오는 패킷 처리 구조

export const onData = (socket) => async (data) => {
  socket.buffer = Buffer.concat([socket.buffer, data]);

  const totalHeaderLength = config.packet.totalLength + config.packet.typeLength;

  while (socket.buffer.length >= totalHeaderLength) {
    const length = socket.buffer.readUInt32BE(0);
    const packetType = socket.buffer.readUInt8(config.packet.totalLength);

    if (socket.buffer.length >= length) {
      const packet = socket.buffer.slice(totalHeaderLength, length);
      socket.buffer = socket.buffer.slice(length);

      try {
        switch (packetType) {
          case PACKET_TYPE.NORMAL:
            const { handlerId, userId, payload } = packetParser(packet);

            const handler = getHandlerById(handlerId);

            await handler({ socket, userId, payload });
        }
      } catch (error) {
        handleError(socket, error);
      }
    } else {
      // 아직 전체 패킷이 도착하지 않음
      break;
    }
  }
};

버퍼 상태

 

 

핸들러 처리 로직