ITeye博客

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

wander_bird · 2015-02-27 10:22 · js&ajax · Web前端 · Markdown

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);
			}
		};

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。