Web COM example
An example showing how Web COM works
by Strawmanbobi
HTML
<!DOCTYPE html>
<body>
<div>
<div>
<span style="margin-top: 5px;">Web COM Example : </span>
<button id="button_start">Start Test</button>
</div>
<div>
<textarea id="received_content" style="margin-top: 5px; width: 320px; height: 120px;" readonly></textarea>
</div>
<div>
<input id="send_content" style="margin-top: 5px;"> <button id="button_send">Send</button>
</div>
</div>
</body>
JavaScript
var ws;
function $(id) {
return document.getElementById(id);
}
window.onload = function () {
$('button_start').addEventListener('click', function() {
startExample();
});
$('button_send').addEventListener('click', function() {
sendData();
});
};
function startExample() {
var address = 'ws://localhost:8301/';
ws = new WebSocket(address);
ws.binaryType = 'arraybuffer';
ws.addEventListener('open', function() {
console.log('socket connected');
});
ws.addEventListener('close', function() {
console.log('socket connection has been closed');
});
ws.addEventListener('message', onDataReceived);
}
function sendData() {
ws.send($('send_content').value);
}
function onDataReceived(e) {
$('received_content').value = $('received_content').value + ab2hex(e.data) + '\r\n';
}
function ab2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => '0x' + ('00' + x.toString(16)).slice(-2)).join(',');
}