Skip to content

Instantly share code, notes, and snippets.

@nnabeyang
Created December 28, 2012 13:25
Show Gist options
  • Select an option

  • Save nnabeyang/4397829 to your computer and use it in GitHub Desktop.

Select an option

Save nnabeyang/4397829 to your computer and use it in GitHub Desktop.
xhr2でバイナリに文字列を埋め込んだデータの送信するテスト。サーバー側の処理はhttps://gist.github.com/4394635を参照してください。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>xhr2 test</title>
<body>
<div>
<h3>インプット</h3>
<p>整数:<input type="text" id="input"/>例:"0x1, 0x3, 0x4"</p>
<p>文字列:<input type="text" id="text-input"/>例: "hello, world"</p>
<button id="send">send</button>
</div>
<h3>レスポンス</h3>
<textarea id="response"></textarea>
<script>
var inputEL = document.getElementById('input');
var textInputEL = document.getElementById('text-input');
var txtArea = document.getElementById('response');
document.getElementById('send').addEventListener('click', function(e) {
var inputs = inputEL.value.split(',');
if(isNaN(parseInt(inputs[0]))) return;
var bufs = [];
var v, buf;
buf = new ArrayBuffer(4);
dv = new DataView(buf);
dv.setUint32(0, inputs.length);
bufs.push(buf);
for(var i = 0; v = inputs[i]; i++) {
buf = new ArrayBuffer(1);
dv = new DataView(buf);
dv.setUint8(0, parseInt(v));
bufs.push(buf);
}
var views = [];
for(var i = 0; bufs[i]; i++) {
views.push(new Uint8Array(bufs[i]));
}
views.push(textInputEL.value);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/send', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var dv;
if(this.status == 200) {
var dv = new DataView(this.response);
var txt = '(';
var size = 4 + dv.getUint32(0);
for(var i = 4; i < size; i++) {
txt += dv.getUint8(i)
if(i == size - 1) txt += ')';
else txt += ',';
}
size = this.response.byteLength;
for(var j = i; j < size; j++) {
txt += String.fromCharCode(dv.getUint8(j));
}
txtArea.value = txt;
} else {
console.log(this.status);
}
};
xhr.send(new Blob(views, {type: 'application/octet-stream'}));
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment