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

c++ 데이타송수신

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

#include <cstddef>  // std::byte를 위한 헤더
#include <sys/socket.h>
#include <memory>  // std::unique_ptr를 위한 헤더
#include <cstring>  // std::memcpy를 위한 헤더

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

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

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

    while (true) {
        ssize_t n = recv(sockfd, header.get(), header_length, 0);  // 헤더 받기
        if (n == -1) {
            // 에러 처리 코드...
        }

        int body_length = getBodyLength(header.get(), n);  // 헤더에서 바디의 길이 파악
        std::unique_ptr<std::byte[]> body(new std::byte[body_length]);  // 바디를 저장할 동적 배열

        n = recv(sockfd, body.get(), body_length, 0);  // 바디 받기
        if (n == -1) {
            // 에러 처리 코드...
        }

        // 헤더와 바디를 합치는 코드...
        std::unique_ptr<std::byte[]> combined(new std::byte[n + body_length]);
        std::memcpy(combined.get(), header.get(), n);
        std::memcpy(combined.get() + n, body.get(), body_length);

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

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

c++ ㆍ데이타송수신 헤더 바디 가변적으로 처리하는법

반응형

댓글