MessageChannel Example
by Gustavo Carvalho
HTML
<script src="http://threadcomm.appspot.com/worker1.js"></script>
<script src="http://threadcomm.appspot.com/worker2.js"></script>
<div>
<h1>Workers communication</h1>
<div id="log">
<div>
<input type="text" placeholder="Enter message..." id="msg" />
<br />
<button id="send1">Send to worker1</button>
<button id="send2">Send to worker2</button>
<br />
<button id="send3">Send to channel from worker1</button>
<button id="send4">Send to channel from worker2</button>
</div>
<br />
</div>
</div>
JavaScript
/**
* @author Raju Konga
*/
var worker1_code = "var channelPort; onmessage = function(e) { if (e.data.code == 'start') { channelPort = e.ports[0]; channelPort.postMessage(e.data.msg+' >> worker1 channel post'); channelPort.onmessage = getChannelMessage; } else if(e.data.code=='msgw') { postMessage(e.data.msg+' >> worker1 got msg'); }else if(e.data.code=='msgch') { channelPort.postMessage(e.data.msg+' >> worker1 got msg'); } } function getChannelMessage(e){ postMessage(e.data+' >> channel recieved msg in worker1 '); }";
var worker2_code = "var channelPort; onmessage = function(e) { if (e.data.code == 'start') { channelPort = e.ports[0]; channelPort.postMessage(e.data.msg+' >> worker2 channel post'); channelPort.onmessage = getChannelMessage; }else if(e.data.code=='msgw') { postMessage(e.data.msg+' >> worker2 got msg'); }else if(e.data.code=='msgch') { channelPort.postMessage(e.data.msg+' >> worker2 got msg'); } } function getChannelMessage(e){ postMessage(e.data+' >> channel recieved msg in worker2'); }";
$(function () {
var worker1 = new Worker("/echo/js/?delay=2&js=" + worker1_code);
var worker2 = new Worker("/echo/js/?delay=2&js=" + worker2_code);
var channel = new MessageChannel();
worker1.onmessage = function (e) {
$("#log").append("<br>" + e.data);
console.log(e.data);
};
worker1.postMessage({
code: "start",
msg: "ping"
}, [channel.port1]);
worker2.onmessage = function (e) {
$("#log").append("<br>" + e.data);
console.log(e.data);
};
worker2.postMessage({
code: "start",
msg: "ping"
}, [channel.port2]);
$("#send1").click(function () {
var msg = $("#msg").val();
if (msg && msg != "start")
worker1.postMessage({
code: "msgw",
msg: "ping2"
});
$("#msg").val("");
});
$("#send2").click(function () {
var msg = $("#msg").val();
if (msg && msg !=...