Search code examples
javascriptjavawebrtc

How to transfer iso-8859-1 encoded byte array from java to javascript via webrtc's data channel


I have a iso-8859-1 encoded byte array, and I want to send it by webrtc's datachannel. But the datachannel seems not to support transfer iso-8859-1 encoded byte array.

I've tried converting its encoding format to utf-8 for transmission. But on the javascript side I can't get it back to the original data. What should I do to implement this functionality?
Here is my code. Please help me.

// java code
public void sendDataChannelMessage(byte[] message, DataChannel dataChannel) {
    if (dataChannel == null) {
        Log.e(TAG, "datachannel is null");
    }

    String data = new String(message, StandardCharsets.UTF_8);
    byte[] msg = data.getBytes(StandardCharsets.UTF_8);
    DataChannel.Buffer buffer = new DataChannel.Buffer(ByteBuffer.wrap(msg), false);
    boolean ret = dataChannel.send(buffer);
    // Log.d(TAG, "send state: " + ret);
}

// javascript code
function handleReceiveMessage(event) {
    const byteArray= new TextEncoder('utf-8').encode(event.data);
    const receivedData = new TextDecoder('iso-8859-1').decode(byteArray);
}

Solution

  • I have solved my problem, the code is very simple. Just send the source data in binary. (Because my source data is binary data of video)

    // java code
    public void sendDataChannelMessage(byte[] message, DataChannel dataChannel) {
        if (dataChannel == null) {
            Log.e(TAG, "datachannel is null");
        }
    
        DataChannel.Buffer buffer = new DataChannel.Buffer(ByteBuffer.wrap(message), true);
        boolean ret = dataChannel.send(buffer);
    }
    
    // javascript code
    function handleReceiveMessage(event) {
        const receivedData = new Uint8Array(event.data);
    }