溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++ Socket庫數(shù)據(jù)分包與合包

發(fā)布時(shí)間:2024-10-27 14:48:52 來源:億速云 閱讀:84 作者:小樊 欄目:編程語言

在C++中,使用Socket庫進(jìn)行數(shù)據(jù)通信時(shí),可能需要將較大的數(shù)據(jù)分割成較小的數(shù)據(jù)包進(jìn)行發(fā)送,以便在網(wǎng)絡(luò)中傳輸。同樣,接收端需要將這些數(shù)據(jù)包重新組合成原始數(shù)據(jù)。這個(gè)過程被稱為數(shù)據(jù)分包與合包。

以下是一個(gè)簡單的示例,展示了如何使用C++ Socket庫進(jìn)行數(shù)據(jù)分包與合包:

#include <iostream>
#include <vector>
#include <cstring>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

const int BUFFER_SIZE = 1024;

void sendData(int sockfd, const std::vector<char>& data) {
    int totalSent = 0;
    while (totalSent < data.size()) {
        int sent = send(sockfd, &data[totalSent], data.size() - totalSent, 0);
        if (sent == -1) {
            perror("send");
            break;
        }
        totalSent += sent;
    }
}

std::vector<char> receiveData(int sockfd, int bufferSize) {
    std::vector<char> buffer(bufferSize);
    int totalReceived = 0;
    while (totalReceived < bufferSize) {
        int received = recv(sockfd, &buffer[totalReceived], bufferSize - totalReceived, 0);
        if (received == -1) {
            perror("recv");
            break;
        } else if (received == 0) {
            break; // Connection closed
        }
        totalReceived += received;
    }
    return std::vector<char>(buffer.begin(), buffer.begin() + totalReceived);
}

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        return 1;
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12345);
    if (inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr) <= 0) {
        perror("inet_pton");
        return 1;
    }

    if (connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        perror("connect");
        return 1;
    }

    std::vector<char> data = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
    sendData(sockfd, data);

    std::vector<char> receivedData = receiveData(sockfd, BUFFER_SIZE);
    std::cout << "Received: " << std::string(receivedData.begin(), receivedData.end()) << std::endl;

    close(sockfd);
    return 0;
}

在這個(gè)示例中,我們使用了sendData函數(shù)將數(shù)據(jù)分包并發(fā)送,然后使用receiveData函數(shù)接收數(shù)據(jù)并將其合包。請(qǐng)注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要更復(fù)雜的錯(cuò)誤處理和數(shù)據(jù)處理邏輯。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI