首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 使用 std::vector 作為 UDP 通信緩衝區的完整指南

     編輯:C++ 入門

為什麼選擇 vector?

在網絡編程中,發送/接收緩衝區大小往往在運行時才能確定。std::vector<char> 提供動態內存管理、連續內存佈局、自動釋放等優勢,是替代裸指針 new char[] 的現代 C++ 最佳實踐。

關鍵技術點

1. 獲取底層緩衝區指針

vector<char> buffer(len);           // 自動初始化為 0
char* ptr = &buffer[0];             // C++03/11 通用寫法
// C++11 可用 buffer.data()

注意:&buffer[0] 才是數據區首地址,&buffer 是 vector 對象自身地址,不可用於 memcpy/sendto。

2. 內存連續性保證

標準保證 vector 元素在內存中連續存放,可直接用於 memcpy、sendto、recvfrom 等系統調用。

3. 大小獲取

使用 buffer.size() 獲取有效數據長度,不要 用 sizeof(buffer)(那會返回 vector 對象大小,通常 24 字節)。

完整 UDP 客戶端示例

#include <Winsock2.h>
#include <vector>
#include <cstring>
#include <iostream>
#pragma comment(lib, "WS2_32.lib")

#define SERVER_PORT 5050
#define BUF_SIZE 1024

struct Point { unsigned short x, y; unsigned char value, U; };
struct Matrix { int num; Point points[100]; };

int main() {
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) return 1;

    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == INVALID_SOCKET) return 1;

    sockaddr_in server{};
    server.sin_family = AF_INET;
    server.sin_port = htons(SERVER_PORT);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    // 準備發送數據
    Matrix mat{};
    mat.num = 2;
    mat.points[0] = {1, 1, 1, 1};
    mat.points[1] = {2, 2, 2, 2};

    int data_len = mat.num * sizeof(Point) + 4; // 實際有效長度
    std::vector<char> send_buf(data_len);
    std::memcpy(&send_buf[0], &mat, data_len); // 複製結構體到 vector

    long count = 0;
    while (true) {
        int sent = sendto(sock, &send_buf[0], data_len, 0,
                          (sockaddr*)&server, sizeof(server));
        if (sent == SOCKET_ERROR) {
            std::cerr << "Send failed: " << WSAGetLastError() << '\n';
            break;
        }
        std::cout << "Sent " << ++count << " times\n";
        Sleep(5);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}

常見錯誤避坑

  • ❌ sendto(sock, (char*)&vec, ...) — 傳遞了 vector 對象地址而非數據地址
  • ❌ sizeof(vec) 作為長度 — 包含 vector 內部指針、size、capacity 等元數據
  • ✅ &vec[0] 或 vec.data() + vec.size()

總結

std::vector<char> 結合 RAII 機制,讓 UDP 緩衝區管理既安全又高效。掌握 data()/size() 正確用法,是現代 C++ 網絡編程的基本功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved