[b]1.建立websocket连接[/b]
var ws = null;
$("#connect").click(function() {
ws = new WebSocket("ws://localhost:8080/storage");
ws.binaryType = "arraybuffer";
[b]2.拼接&发送byte array[/b]
String.prototype.getBytes = function() {
var bytes = [];
for (var i = 0; i < this.length; i++) {
var charCode = this.charCodeAt(i);
var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
for (var j = 0; j < cLen; j++) {
bytes.push((charCode << (j*8)) & 0xFF);
}
}
return bytes;
}
var test = "hello world!"
var buffer = new ArrayBuffer(test.length);
var intView = new Int8Array(buffer);
for(var i = 0; i < intView.length; i++){
intView[i]=test.getBytes()[i];
}
ws.send(intView);
[b]3.接收&处理byte array[/b]
ws.onmessage = function(event) {
if (/^\[object (?:Uint8Array|ArrayBuffer)(?:Constructor)?\]$/.test(event.data)){
var bufView = new Uint8Array(event.data);
var unis = [];
for (var i = 0; i < bufView.length; i++) {
unis.push(bufView[i]);
}
console.log('Received from extract: '+String.fromCharCode.apply(null, unis));
}else{
console.log('Received from extract: '+event.data);
}
};