Skip to content

Instantly share code, notes, and snippets.

@mamrehn
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamrehn/a017642f26cdae6fdec1 to your computer and use it in GitHub Desktop.
Save mamrehn/a017642f26cdae6fdec1 to your computer and use it in GitHub Desktop.
Binary Websocket Test

Quick way to test binary websocket API behaviour.

Example outcome:

# Up
object [object ArrayBuffer], Key data: 38, String data: ☁
string , Key data: 38, String data: ☁

# Down
object [object ArrayBuffer], Key data: 40, String data: ⠁
string , Key data: 40, String data: ⠁

#Left
object [object ArrayBuffer], Key data: 37, String data: ━
string , Key data: 37, String data: ━

#Right
object [object ArrayBuffer], Key data: 39, String data: ✁
string , Key data: 39, String data: ✁

# Strg + c
object [object ArrayBuffer], Key data: 17, String data: ᄁ
object [object ArrayBuffer], Key data: 67, String data: 䌁
string , Key data: 67, String data: 䌁
string , Key data: 17, String data: ᄁ
<!DOCTYPE html>
<html>
<head>
<title>Binary Websocket Test</title>
</head>
<body>
<script type="text/javascript">
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://echo.websocket.org');
connection.binaryType = "arraybuffer";
connection.onmessage = function(event) {
var node = document.getElementById('log');
var t = typeof(event.data) + ' ' + event.data;
if (event.data instanceof ArrayBuffer){
// 1 === new Uint8Array(event.data)[0]
t += ', Key data: ' + new Uint8Array(event.data)[1];
t += ', String data: ' + String.fromCharCode.apply(null, new Uint16Array(event.data));
}
var para = document.createElement("p");
para.innerHTML = t;
node.appendChild(para);
};
window.onkeydown = function(e) {
var byteArray = new Uint8Array(2);
byteArray[0] = 1;
byteArray[1] = e.keyCode;
connection.send(byteArray.buffer);
};
window.onkeyup = function(e) {
var c = String.fromCharCode(e.keyCode * 256 + 1)
connection.send(', Key data: '+ e.keyCode + ', String data: ' + c);
};
</script>
<h2>Binary Websocket Test</h2>
<p>Log:</p>
<div style="margin-left: 6px; padding-left: 2px;" id="log"></div>
</body>
</html>
@mamrehn
Copy link
Author

mamrehn commented May 20, 2015

Test it at Plunker.

@mamrehn
Copy link
Author

mamrehn commented May 20, 2015

Instead of the String.fromCharCode.apply function you may also use the new Encoding API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment