Skip to content

Instantly share code, notes, and snippets.

@sang4lv
Created January 3, 2013 13:32
Show Gist options
  • Save sang4lv/4443484 to your computer and use it in GitHub Desktop.
Save sang4lv/4443484 to your computer and use it in GitHub Desktop.
Web Sockets: Introduction
var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
function sendData(type, content) {
if(type == "string") {
connection.send(content);
} else if(type == "blob") {
connection.send(file);
} else if(type == "arraybuffer") {
connection.binaryType = "arraybuffer";
connection.onmessage = function(event) {
console.log(event.data.byteLength);
};
var binary = new Uint8Array(content.data.length);
for (var i = 0; i < content.data.length; i++) {
binary[i] = content.data[i];
}
connection.send(binary.buffer);
}
}
//String
sendData("string", "Hello There!");
//BLOB
var files = document.querySelect("input[type='file']").files;
for(var i = 0; i < files.length; i++) {
sendData("document", files[i]);
}
//Array Buffer
var img = canvas_context.getImageData(0, 0, 400, 320);
sendData("arraybuffer", img);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment