본문 바로가기
프로그래밍 _공부자료./C++ 공부

c++ soket통신 receive header와 body

by 대구부자 2023. 11. 10.
반응형

#include <vector>
#include <cstddef>  // std::byte를 위한 헤더
#include <sys/socket.h>
#include <algorithm>  // std::copy를 위한 헤더

int main() {
    int sockfd;  // 소켓 파일 디스크립터
    // sockfd 초기화하는 코드...

    int header_length = 100;  // 헤더의 길이

    std::vector<std::byte> header(header_length);  // 헤더를 저장할 동적 배열

    while (true) {
        ssize_t n = recv(sockfd, header.data(), header.size(), 0);  // 헤더 받기
        if (n == -1) {
            // 에러 처리 코드...
        }
        header.resize(n);  // 실제로 받은 데이터만큼 크기 조정

        int body_length = getBodyLength(header);  // 헤더에서 바디의 길이 파악
        std::vector<std::byte> body(body_length);  // 바디를 저장할 동적 배열

        n = recv(sockfd, body.data(), body.size(), 0);  // 바디 받기
        if (n == -1) {
            // 에러 처리 코드...
        }
        body.resize(n);  // 실제로 받은 데이터만큼 크기 조정

        // 헤더와 바디를 합치는 코드...
        std::vector<std::byte> combined(header.size() + body.size());
        std::copy(header.begin(), header.end(), combined.begin());
        std::copy(body.begin(), body.end(), combined.begin() + header.size());

        // combined를 이용한 처리 코드...
    }
}

int getBodyLength(const std::vector<std::byte>& header) {
    // header에서 바디의 길이를 파악하여 반환하는 코드...
}

c++ 통신 헤더와 바디 나눠 받기

반응형

댓글