Fikir setInterval ve Sockets'in arkasındadır, setInterval çoğu tarayıcıda desteklenir ve Javascript WbsocketApi hemen hemen her tarayıcıda desteklenir.
Kısa genel bakış: setInterval () - Bu işlev davranışı, bilgisayarınız uyku / askıya alınmış / hazırda bekletme modundayken duraklatılır ve uyanma modundayken kendini devam ettirir.
Aşağıdaki kod ilk önce (belki de aynı zamanda ama) aşağıdakileri yapar, bağlantıları dinlemeye php server_socket başlatır,
javascript websocket api, Unix zaman damgası milisaniye cinsinden geçerli zaman damgasını her 2 saniyede gönderir, size 1 saniye sürebilir.
Bundan sonra php sunucu soketi bu kez alıyor ve karşılaştırmak için önceki zaman gibi bir şey olup olmadığını kontrol eder, kod ilk örneklendiğinde php javascript websocket gönderilen zamanla karşılaştırmak için önceki zaman gibi bir şey yok, bu yüzden php "prev_time" adlı oturumda bu kez kaydedilen hiçbir şey yapmaz ve javascript soketinden başka bir zaman verisinin alınmasını bekler, dolayısıyla burada ikinci döngü başlar. php sunucu soketi javascript WebsocketApi'den yeni zaman verileri sokulduğunda, bu yeni alınan zaman verileri ile karşılaştırmak için önceki zamana benzer bir şey olup olmadığını kontrol eder, php, 'prev_time' adı verilen oturumun var olup olmadığını kontrol eder, çünkü ikinci döngüde php, var, değerini alıyor ve takip ediyor$diff = $new_time - $prev_time, $ diff 2 saniye veya 2000 milisaniye olacaktır çünkü setInterval döngümüzün her 2 saniyede bir gerçekleştiğini ve gönderdiğimiz zaman biçiminin milisaniye olduğunu unutmayın,
php if($diff<3000), kullanıcının aktif olduğunu biliyorsa farkın 3000'den az olup olmadığını kontrol eder , yine bu saniyeleri istediğiniz gibi manipüle edebilirsiniz, 3000'i seçiyorum çünkü ağda neredeyse imkansız olan olası gecikme, ancak her zaman dikkatli olduğumu biliyorsunuz bu ağlara gelir, bu yüzden php kullanıcının aktif olduğunu belirlediğinde php sadece $new_timeyeni alınan değeri ile 'prev_time' oturumunu sıfırlar ve sadece test amacıyla javascript soketine mesaj gönderir,
ancak $diff3000'den fazla ise, bir şey setInterval'ı duraklattı demektir ve bunun tek yolu olabilir ve bence ne dediğimi zaten biliyorsunuzdur, bu nedenle else( if($diff<3000)) mantığında, belirli oturumu yok ederek kullanıcıyı kapatabilirsiniz ve yeniden yönlendirmek istiyorsanız, javacript soketine bazı metinler gönderebilir window.location = "/login"ve metne bağlı olarak yürütülecek bir mantık oluşturabilirsiniz , işte burada kod:
İlk olarak sadece javascript yüklemek için index.html dosyasıdır:
<html>
<body>
<div id="printer"></div>
<script src="javascript_client_socket.js"></script>
</body>
</html>
o zaman gerçekten güzel bir şekilde kodlanmamış bir javascripttir, ancak ÖNEMLİ OLDUĞU YORUMLARI okuyabilirsiniz:
var socket = new WebSocket('ws://localhost:34237'); // connecting to socket
// Open the socket
socket.onopen = function(event) { // detecting when connection is established
setInterval(function(){ //seting interval for 2 seconds
var date = new Date(); //grabing current date
var nowtime = Date.parse(date); // parisng it in miliseconds
var msg = 'I am the client.'; //jsut testing message
// Send an initial message
socket.send(nowtime); //sending the time to php socket
},2000);
};
// Listen for messages
socket.onmessage = function(event) { //print text which will be sent by php socket
console.log('php: ' + event.data);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};
şimdi burada php kodunun bir parçası, endişelenmeyin aşağı tam kod da var ama bu kısım aslında yukarıda belirtilen işleri de diğer işlevleri karşılayacak ama onlar çözme ve javascript yuvaları ile çalışmak için bu yüzden gerçek bir şey doğru burada ÖNEMLİ YORUMLARI OKUYUN:
<?php
$decoded_data = unmask($data /* $data is actual data received from javascript socket */); //grabbing data and unmasking it | unmasking is for javascript sockets don't mind this
print("< ".$decoded_data."\n");
$response = strrev($decoded_data);
$jsTime = (int) $decoded_data; /* time sent by javascript in MILISECONDS IN UNIX FORMAT */
if (isset($_SESSION['prev_time'])) { /** check if we have stored previous time in the session */
$prev_time = (int) $_SESSION['prev_time']; /** grabbing the previous time from session */
$diff = $jsTime-$prev_time; /** getting the difference newly sent time and previous time by subtracting */
print("$jsTime - $prev_time = $diff"); /** printing the difference */
if($diff<3000){ /** checking if difference is less than 3 second if it is it means pc was not at sleep
*** you can manipulate and have for example 1 second = 1000ms */
socket_write($client,encode("You are active! your pc is awakend"));
$_SESSION['prev_time'] = $jsTime; /** saving newly sent time as previous time for future testing whcih will happen in two seconds in our case*/
}else { /** if it is more than 3 seconds it means that javascript setInterval function was paused and resumed after 3 seconds
** So it means that it was at sleep because when your PC is at sleep/suspended/hibernate mode setINterval gets pauesd */
socket_write($client,encode("You are not active! your pc is at sleep"));
$_SESSION['prev_time'] = $jsTime;
}
}else { /** if we have not saved the previous time in session save it */
$_SESSION['prev_time'] = $jsTime;
}
print_r($_SESSION);
?>
Ve burada php tam kodu:
<?php
//Code by: Nabi KAZ <www.nabi.ir>
session_abort();
// set some variables
$host = "127.0.0.1";
$port = 34237;
date_default_timezone_set("UTC");
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0)or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port)or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 20)or die("Could not set up socket listener\n");
$flag_handshake = false;
$client = null;
do {
if (!$client) {
// accept incoming connections
// client another socket to handle communication
$client = socket_accept($socket)or die("Could not accept incoming connection\n");
}
$bytes = @socket_recv($client, $data, 2048, 0);
if ($flag_handshake == false) {
if ((int)$bytes == 0)
continue;
//print("Handshaking headers from client: ".$data."\n");
if (handshake($client, $data, $socket)) {
$flag_handshake = true;
}
}
elseif($flag_handshake == true) {
/*
**** Main section for detectin sleep or not **
*/
if ($data != "") {
$decoded_data = unmask($data /* $data is actual data received from javascript socket */); //grabbing data and unmasking it | unmasking is for javascript sockets don't mind this
print("< ".$decoded_data."\n");
$response = strrev($decoded_data);
$jsTime = (int) $decoded_data; /* time sent by javascript in MILISECONDS IN UNIX FORMAT */
if (isset($_SESSION['prev_time'])) { /** check if we have stored previous time in the session */
$prev_time = (int) $_SESSION['prev_time']; /** grabbing the previous time from session */
$diff = $jsTime-$prev_time; /** getting the difference newly sent time and previous time by subtracting */
print("$jsTime - $prev_time = $diff"); /** printing the difference */
if($diff<3000){ /** checking if difference is less than 3 second if it is it means pc was not at sleep
*** you can manipulate and have for example 1 second = 1000ms */
socket_write($client,encode("You are active! your pc is awakend"));
$_SESSION['prev_time'] = $jsTime; /** saving newly sent time as previous time for future testing whcih will happen in two seconds in our case*/
}else { /** if it is more than 3 seconds it means that javascript setInterval function was paused and resumed after 3 seconds
** So it means that it was at sleep because when your PC is at sleep/suspended/hibernate mode setINterval gets pauesd */
socket_write($client,encode("You are not active! your pc is at sleep"));
$_SESSION['prev_time'] = $jsTime;
}
}else { /** if we have not saved the previous time in session save it */
$_SESSION['prev_time'] = $jsTime;
}
print_r($_SESSION);
/*
**** end of Main section for detectin sleep or not **
*/
}
}
} while (true);
// close sockets
socket_close($client);
socket_close($socket);
$client = null;
$flag_handshake = false;
function handshake($client, $headers, $socket) {
if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
$version = $match[1];
else {
print("The client doesn't support WebSocket");
return false;
}
if ($version == 13) {
// Extract header variables
if (preg_match("/GET (.*) HTTP/", $headers, $match))
$root = $match[1];
if (preg_match("/Host: (.*)\r\n/", $headers, $match))
$host = $match[1];
if (preg_match("/Origin: (.*)\r\n/", $headers, $match))
$origin = $match[1];
if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
$key = $match[1];
$acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Sec-WebSocket-Accept: $acceptKey".
"\r\n\r\n";
socket_write($client, $upgrade);
return true;
} else {
print("WebSocket version 13 required (the client supports version {$version})");
return false;
}
}
function unmask($payload) {
$length = ord($payload[1]) & 127;
if ($length == 126) {
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
}
elseif($length == 127) {
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
}
else {
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
}
$text = '';
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i % 4];
}
return $text;
}
function encode($text) {
// 0x1 text frame (FIN + opcode)
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)$header = pack('CCS', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCN', $b1, 127, $length);
return $header.$text;
}
NOT IT READ:
$new_timedeğişken $jsTimeKodda
klasör oluşturmak ve sadece kopyalayıp yapıştırın php soket komut ile dosyaları yapıştırın: php -f server_socket.php localhost gidin ve "aktif" veya "aktif değil" diyecek mesajları görmek için konsolu açık test (uykudan geldiğinizde); uygulamanız kullanıcı uyku modundayken değil uykudan geldiğinde gerçekleşecektir, çünkü o anda her şey pagefile (windows) veya swap (linux) içinde önbelleğe alınır