Websocket for binary transfer of data & decode with HTML5

WebSockets can handle binary data transfer using base64 encoding/decoding. Modern browsers provide built-in methods window.btoa() for encoding and window.atob() for decoding base64 data.

Base64 Encoding for Binary Transfer

When transferring binary data through WebSockets, encode it as base64 on the client side before sending:

<!DOCTYPE html>
<html>
<body>
    <script>
        // Create WebSocket connection
        const socket = new WebSocket('ws://localhost:8080');
        
        // Convert binary data to base64
        function binaryToBase64(binaryData) {
            return window.btoa(binaryData);
        }
        
        // Send binary data as base64
        function sendBinaryData() {
            const binaryString = "Hello Binary World!";
            const encoded = binaryToBase64(binaryString);
            
            console.log("Original:", binaryString);
            console.log("Encoded:", encoded);
            
            // socket.send(encoded); // Uncomment when server is running
        }
        
        sendBinaryData();
    </script>
</body>
</html>
Original: Hello Binary World!
Encoded: SGVsbG8gQmluYXJ5IFdvcmxkIQ==

Base64 Decoding Received Data

On the receiving end, decode the base64 data back to its original binary format:

<!DOCTYPE html>
<html>
<body>
    <script>
        // Decode base64 back to binary
        function base64ToBinary(base64String) {
            return window.atob(base64String);
        }
        
        // Simulate receiving base64 encoded data
        function handleReceivedData() {
            const receivedBase64 = "SGVsbG8gQmluYXJ5IFdvcmxkIQ==";
            const decoded = base64ToBinary(receivedBase64);
            
            console.log("Received Base64:", receivedBase64);
            console.log("Decoded Binary:", decoded);
        }
        
        handleReceivedData();
        
        // WebSocket event handler example
        // socket.onmessage = function(event) {
        //     const decodedData = base64ToBinary(event.data);
        //     console.log("Binary data received:", decodedData);
        // };
    </script>
</body>
</html>
Received Base64: SGVsbG8gQmluYXJ5IFdvcmxkIQ==
Decoded Binary: Hello Binary World!

WebSocket Proxy for TCP Connections

The wsproxy tool acts as a bridge between WebSockets and TCP sockets. It automatically handles base64 encoding/decoding of all traffic between the browser and TCP servers.

Browser WebSocket wsproxy Base64 Encode/Decode Bridge TCP Server Raw Binary Base64 Binary

Complete WebSocket Binary Transfer Example

<!DOCTYPE html>
<html>
<body>
    <div id="output"></div>
    
    <script>
        function log(message) {
            document.getElementById('output').innerHTML += message + '<br>';
            console.log(message);
        }
        
        // WebSocket client for binary data transfer
        class BinaryWebSocket {
            constructor(url) {
                this.socket = new WebSocket(url);
                this.setupEventHandlers();
            }
            
            setupEventHandlers() {
                this.socket.onopen = () => {
                    log('WebSocket connection opened');
                };
                
                this.socket.onmessage = (event) => {
                    // Decode received base64 data
                    try {
                        const decodedData = window.atob(event.data);
                        log('Received binary data: ' + decodedData);
                    } catch (e) {
                        log('Received text data: ' + event.data);
                    }
                };
                
                this.socket.onerror = (error) => {
                    log('WebSocket error: ' + error);
                };
            }
            
            sendBinary(data) {
                // Encode binary data as base64 before sending
                const encoded = window.btoa(data);
                this.socket.send(encoded);
                log('Sent encoded data: ' + encoded);
            }
        }
        
        // Example usage (would need actual WebSocket server)
        log('Binary WebSocket client initialized');
        log('Use window.btoa() to encode: ' + window.btoa('test data'));
        log('Use window.atob() to decode: ' + window.atob('dGVzdCBkYXRh'));
        
        // const client = new BinaryWebSocket('ws://localhost:8080');
        // client.sendBinary('Hello Binary!');
    </script>
</body>
</html>
Binary WebSocket client initialized
Use window.btoa() to encode: dGVzdCBkYXRh
Use window.atob() to decode: test data

Key Points

  • window.btoa() encodes binary data to base64 for transmission
  • window.atob() decodes base64 back to binary format
  • wsproxy handles automatic encoding/decoding between WebSocket and TCP
  • All modern browsers support base64 encoding/decoding methods

Conclusion

WebSocket binary data transfer relies on base64 encoding for compatibility. Use btoa() and atob() for encoding/decoding, and consider wsproxy for TCP bridge connections with automatic base64 handling.

Updated on: 2026-03-15T23:18:59+05:30

908 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements