JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-json/2.5.1/jquery.json.min.js"></script>
<script src="https://raw.githubusercontent.com/jbloemendal/jquery-simple-websocket/master/jquery.simple.websocket.min.js"></script>
JavaScript
//PROCESSED POINT HOLDERS
var points = {}; // { '3;-4' : true, '3;4': false }
var pointsArray = []; // [ {x: 3, y: 4}, {x: -3, y: 4}]
//SOCKET INIT
var socket = $.simpleWebSocket({
url: 'wss://echo.websocket.org/',
timeout: 10000, // optional, default timeout between connection attempts
attempts: 5,
dataType: 'json'
});
//SERVER SIDE INFRASTRUCTURE, WE NEED TO EMULATE REMOTE HOST
var socketServerEmulator = function(messageJson) {
if (messageJson && messageJson.mtype) {
switch (messageJson.mtype) {
case 'request':
var result = (messageJson.x + messageJson.y) % 2 === 0;
console.log('SERVER EMULATOR: Got request', messageJson);
console.log('SERVER EMULATOR: SENDING GENERATED RESPONSE...');
socket.send({
'mtype': 'response',
'x': messageJson.x,
'y': messageJson.y,
'status': result
})
break;
case 'response':
console.log('SERVER EMULATOR: Passing through response: ', messageJson);
break;
default:
break;
}
}
}
//// CLIENT SIDE CODE ////
function processResponse(responseJson, promise) {
if (!responseJson.mtype || responseJson.mtype != 'response') {
return false;
}
console.log('CLIENT: Processing response...');
if (responseJson.status) {
var x = responseJson.x;
var y = responseJson.y;
//Saving data to points array
points[x + ';' + y] = true;
pointsArray.push({
'x': x,
'y': y
});
promise.resolve(true);
} else {
promise.resolve(false);
}
console.log('CLIENT: Response processed.');
}
function getCell(x, y) {
var cellPromise = $.Deferred();
setTimeout(function() {
socket.listen(function(json) {
processResponse(json, cellPromise);
socket.remove(this);
});
socket.send({
'mtype': 'request',
'x': x,
'y': y
});
}, 10);
return cellPromise;
}
//// SAMPLE USAGE ////
if (socket && !socket.isConnected()) {
...