Huffman Coding Example: Optimized Networking

Transferring data across a network can be a time-consuming process, particularly across slow wide-area networks. One approach to managing this problem is to compress the data before sending it and then uncompress it when it is received. Although sometimes the time spent compressing and uncompressing data may not be worth the savings in time across the network, in many network applications this cost is well justified. This example presents two functions, send_comp and recv_comp (see Example 14.4), that send and receive data in a compressed format.

The send_comp function sends data by first compressing it and then calling the standard socket function send. To send the data, send_comp requires four arguments: s is a socket descriptor for which a connection has already been established, data is the buffer of data to send, size is the size of the data, and flags is the normal flags argument passed to send. To begin the sending process, we compress the data in data by calling huffman_compress. Next, we send the size of the compressed data, as returned by huffman_compress, so that space can be allocated on the receiving end. This is part of a simple protocol we establish with the receiver. Last, we send the compressed data itself and then free it as the interface to huffman_compress suggests.

The recv_comp function uses the standard socket function recv to receive data sent by send_comp. To receive the data, recv_comp requires four arguments: ...

Get Mastering Algorithms with C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.