chromium/third_party/blink/web_tests/http/tests/websocket/receive-arraybuffer.html

<!DOCTYPE html>
<html>
<head>
<script src="/js-test-resources/js-test.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
description("WebSocket: Receive ArrayBuffers.");

window.jsTestIsAsync = true;

function createArrayBufferContainingHelloWorld()
{
    var hello = "Hello, world!";
    var array = new Uint8Array(hello.length);
    for (var i = 0; i < hello.length; ++i)
        array[i] = hello.charCodeAt(i);
    return array.buffer;
}

function createEmptyArrayBuffer()
{
    return new ArrayBuffer(0);
}

function createArrayBufferContainingAllDistinctBytes()
{
    var array = new Uint8Array(256);
    for (var i = 0; i < 256; ++i)
        array[i] = i;
    return array.buffer;
}

var ws = new WebSocket("ws://127.0.0.1:8880/binary-frames");
ws.binaryType = "arraybuffer";
shouldBeEqualToString("ws.binaryType", "arraybuffer");

var closeEvent;
var receivedMessages = [];
var expectedValues = [createArrayBufferContainingHelloWorld(), createEmptyArrayBuffer(), createArrayBufferContainingAllDistinctBytes()];

ws.onmessage = function(event)
{
    receivedMessages.push(event.data);
};

ws.onclose = function(event)
{
    closeEvent = event;

    shouldEvaluateTo("receivedMessages.length", expectedValues.length);
    for (var i = 0; i < expectedValues.length; ++i)
        check(i);
    finishJSTest();
};

var responseType;

function check(index)
{
    debug("Checking message #" + index + ".");
    responseType = '' + receivedMessages[index];
    shouldBeEqualToString("responseType", "[object ArrayBuffer]");
    checkArrayBuffer(index, receivedMessages[index], expectedValues[index]);
}

var actualArray;
var expectedArray;

function checkArrayBuffer(testIndex, actual, expected)
{
    actualArray = new Uint8Array(actual);
    expectedArray = new Uint8Array(expected);
    shouldEvaluateTo("actualArray.length", expectedArray.length);
    // Print only the first mismatched byte in order not to flood console.
    for (var i = 0; i < expectedArray.length; ++i) {
        if (actualArray[i] != expectedArray[i]) {
            testFailed("Value mismatch: actualArray[" + i + "] = " + actualArray[i] + ", expectedArray[" + i + "] = " + expectedArray[i]);
            return;
        }
    }
    testPassed("Passed: Message #" + testIndex + ".");
}

</script>
</body>
</html>