websocket下js发送和接受byte array信息

1.建立websocket连接
var ws = null;
	$("#connect").click(function() {
		ws = new WebSocket("ws://localhost:8080/storage");
		ws.binaryType = "arraybuffer";

2.拼接&发送byte array
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);


3.接收&处理byte array
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);
			}
		};

你可能感兴趣的:(Ajax)