Skip to content

Instantly share code, notes, and snippets.

@fillano
Created April 24, 2012 03:28
Show Gist options
  • Save fillano/2476177 to your computer and use it in GitHub Desktop.
Save fillano/2476177 to your computer and use it in GitHub Desktop.
worked fine with node-websocket server. websocket now supports both utf8 and binary data frame.
<html>
<body>
<input id="msg" type="text">
<input id="send" type="button" value="send">
<input id="file" type="file">
<div id="panel" style="border:solid 1px #336699"></div>
<div id="info" style="border:solid 1px #336699"></div>
<div id="img"><img id="imgtarget"></div>
</body>
</html>
<script>
var ws = new WebSocket('ws://localhost:8000', 'echo-protocol');
document.getElementById('send').addEventListener('click', function(e) {
var val = document.getElementById('msg');
ws.send(val.value);
val.value = '';
}, false);
ws.addEventListener('message', function(msg) {
document.getElementById('panel').innerHTML = msg.data;
var str = '[received from ws]<br>';
for(var i in msg.data) {
str += i + ': ' + msg.data[i] + '<br>';
}
if(msg.data.toString().indexOf('Blob')>-1) {
var url = window.URL || window.webkitURL || {createObjectURL:function(){return '';}};
console.log(url.createObjectURL(msg.data));
document.getElementById('imgtarget').src = url.createObjectURL(msg.data);
} else {
document.getElementById('info').innerHTML = str;
}
console.log(ws);
}, false);
ws.addEventListener('error', function(err){
console.log(err);
}, false);
document.getElementById('file').addEventListener('change', function(e){
var str = '[ready for send]<br>';
var filereader = new FileReader();
var file = e.target.files[0];
str += file.toString() + '<br>';
for(var i in file) {
str += i + ': ' + file[i] + '<br>';
}
document.getElementById('info').innerHTML = str;
try {
ws.send(file);
} catch(e) {
console.log(e);
}
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment