萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

自製輕量級 Web 伺服器實現 gzip 壓縮傳輸(C 語言 + zlib)

專案背景

在 Ubuntu 上從零撰寫一個極簡 HTTP 伺服器,監聽 1024 埠,支援 gzip 壓縮回應,驗證壓縮頭部格式與 zlib 串流壓縮流程。適合學習 HTTP 協定、zlib 用法、Socket 程式設計。

核心程式碼結構

#include <zlib.h>
#define DEFAULT_BUFFERSIZE 8096
static const char gzip_header[10] = {0x1f, 0x8b, Z_DEFLATED, 0, 0, 0, 0, 0, 0, 0x03}; // RFC 1952 標準 gzip header

int gzip_buffer(int sockd, char *msg, int len) {
    z_stream stream;
    char in[DEFAULT_BUFFERSIZE];
    char send[DEFAULT_BUFFERSIZE + 18]; // header(10) + data + trailer(8)
    memcpy(send, gzip_header, 10);
    memcpy(in, msg, len);

    stream.zalloc = Z_NULL;
    stream.zfree = Z_NULL;
    stream.opaque = Z_NULL;
    deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);

    stream.avail_in = len;
    stream.next_in = (Bytef*)in;
    stream.avail_out = DEFAULT_BUFFERSIZE;
    stream.next_out = (Bytef*)(send + 10);

    deflate(&stream, Z_FINISH);
    unsigned have = DEFAULT_BUFFERSIZE - stream.avail_out;

    // CRC32 + ISIZE (原始長度) 寫入 trailer
    unsigned long crc = crc32(0L, (Bytef*)in, len);
    char *tail = send + 10 + have;
    tail[0] = crc & 0xff; tail[1] = (crc>>8) & 0xff; tail[2] = (crc>>16) & 0xff; tail[3] = (crc>>24) & 0xff;
    tail[4] = len & 0xff; tail[5] = (len>>8) & 0xff; tail[6] = (len>>16) & 0xff; tail[7] = (len>>24) & 0xff;

    write(sockd, send, have + 18);
    deflateEnd(&stream);
    return 1;
}

完整編譯與執行

# 安裝 zlib 開發套件
sudo apt-get install zlib1g-dev

# 編譯
gcc -o reage_web reage_web.c -lz

# 執行(需 root 權限綁定 1024 以下埠,或改用 >1024 埠)
./reage_web

# 瀏覽器訪問 https://localhost:1024 應看到壓縮後的 HTML 內容

關鍵點解析

  • gzip header:10 bytes,固定魔數 0x1f 0x8b、壓縮方法 Z_DEFLATED、旗標、修改時間、額外旗標、OS 代碼(0x03=Unix)。
  • deflateInit2:windowBits = -MAX_WBITS 表示輸出 gzip 格式(而非 zlib/raw deflate)。
  • trailer:CRC-32 + ISIZE (原始資料長度 mod 2^32),均為 little-endian。
  • HTTP 回應頭:必須包含 Content-Encoding: gzip,否則瀏覽器不會解壓。

原始碼下載

百度網盤(含 Makefile)

擴充方向

  • 支援 Accept-Encoding 協商壓縮。
  • 加入靜態檔案服務、MIME 類型對應、非阻塞 I/O(epoll/kqueue)。
  • 移植至嵌入式裝置(交叉編譯、裁剪 zlib)。
copyright © 萬盛學電腦網 all rights reserved