1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-03 09:49:28 +02:00
and Socket improvements
This commit is contained in:
DanielnetoDotCom 2021-01-15 10:03:09 -03:00
parent e00c0d7022
commit ee3fabaad8
10 changed files with 225 additions and 63 deletions

View file

@ -1,28 +1,35 @@
var socketMyResourceId = 0;
var socketConnectRequested = 0;
function socketConnect() {
if(socketConnectRequested){
return false;
}
socketConnectRequested = 1;
console.log('Trying to reconnect on ' + webSocketURL);
conn = new WebSocket(webSocketURL);
conn.onopen = function (e) {
console.log("Socket onopen", e);
socketMyResourceId = 0;
sendSocketMessage("webSocketToken", "");
sendSocketMessageToNone("webSocketToken", "");
return false;
};
conn.onmessage = function (e) {
console.log("Socket onmessage", e);
//console.log("Socket onmessage", e);
var json = JSON.parse(e.data);
console.log("Socket onmessage", json);
if (!socketMyResourceId) {
socketMyResourceId = parseInt(e.data);
socketMyResourceId = parseInt(json.ResourceId);
var msg = "Socket socketMyResourceId " + socketMyResourceId;
sendSocketMessage(msg, "");
//sendSocketMessage(msg, "", "");
console.log(msg);
} else {
var json = JSON.parse(e.data);
var myfunc;
if (json.callback) {
var code = "if(typeof " + json.callback + " == 'function'){myfunc = " + json.callback + ";}else{myfunc = defaultCallback;}";
console.log(code);
//console.log(code);
eval(code);
} else {
console.log("onmessage: callback not found");
myfunc = defaultCallback;
}
myfunc(json);
@ -30,6 +37,7 @@ function socketConnect() {
};
conn.onclose = function (e) {
socketConnectRequested = 0;
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function () {
socketConnect();
@ -37,18 +45,27 @@ function socketConnect() {
};
conn.onerror = function (err) {
socketConnectRequested = 0;
console.error('Socket encountered error: ', err.message, 'Closing socket');
conn.close();
};
}
function sendSocketMessage(msg, callback) {
function sendSocketMessageToAll(msg, callback) {
sendSocketMessageToUser(msg, callback, "");
}
function sendSocketMessageToNone(msg, callback) {
sendSocketMessageToUser(msg, callback, -1);
}
function sendSocketMessageToUser(msg, callback, users_id) {
if (conn.readyState === 1) {
conn.send(JSON.stringify({msg: msg, webSocketToken: webSocketToken, callback: callback}));
conn.send(JSON.stringify({msg: msg, webSocketToken: webSocketToken, callback: callback, users_id, users_id}));
} else {
console.log('Socket not ready send message in 1 second');
setTimeout(function () {
sendSocketMessage(msg, callback);
sendSocketMessageToUser(msg, callback, to_users_id);
}, 1000);
}
}
@ -69,10 +86,9 @@ function isSocketActive(){
}
function defaultCallback(json) {
console.log('defaultCallback', json);
//console.log('defaultCallback', json);
}
$(function () {
socketConnect();
sendSocketMessage("test", "");
});