Socket.send() not send - javascript

Im using PHP socket and im trying to connect it using js .
my JS code is :
var socket = new WebSocket("ws://localhost:9090/");
setTimeout(
socket.onopen = function()
{
try {
socket.send('\n');
}catch (e){
alert(e);
}
try {
socket.send('{"link":"1"}');
}catch (e){
alert(e);
}
alert("Connected");
// Web Socket is connected, send data using send()
}
, 5000);
And PHP code is :
$host = '127.0.0.1';
$port = '9090';
$null = NULL;
include_once ("TransmissionRPC.php");
$rpc = new TransmissionRPC();
$rpc->return_as_array = true;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
socket_set_block($socket);
$clients = array($socket);
while(true){
$changed = $clients;
socket_select($changed, $null, $null, 0, 10);
if (in_array($socket, $changed)){
$socket_new = socket_accept($socket);
$clients[] = $socket_new;
print_r($clients);
$header = socket_read($socket_new, 1024);
perform_handshaking($header, $socket_new, $host, $port);
socket_getpeername($socket_new, $ip);
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
foreach($changed as $changed_socket){
while($input = socket_read($changed_socket, 1024)){
print_r($input);
$received_text = trim($input);
$recived = json_decode($received_text);
if (array_key_exists('session', $recived)){
$session_id = $recived->{'session'};
$info = $rpc->get($session_id, array());
send_message(json_encode($info), 1);
} else if(array_key_exists('link', $recived)) {
$link = $recived->{'link'};
$result = $rpc->sstats();
$test_torrent = "http://www.slackware.com/torrents/slackware64-13.1-install-dvd.torrent";
$result = $rpc->add( $test_torrent, '/home/ftpacc/domains/ali.com/public_html/' );
send_message(json_encode($result), 1);
}
break 2;
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) {
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected \n')));
echo "DC";
}
}
}
function perform_handshaking($receved_header, $client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach ($lines as $line){
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
}
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif ($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif ($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header . $text;
}
function send_message($msg, $reciver_id)
{
global $clients;
#socket_send($clients[$reciver_id] , $msg , strlen($msg) , 0);
var_dump($clients);
return true;
}
When im using socket.send('{"link":"1"}'); not working .
Its give me this error :
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
How can i fix this problem ?
Notice : Its working when im connecting to socket via TELNET .

Related

JavaScript WebSocket & PHP Socket

I want to make a socket connection using JavaScript and PHP.
I use JS WebSocket and PHP Socket.
If I run PHP scripts locally on the server, then they communicate with each other and the connection occurs (screenshot 1).
After the script ends on the server, the socket is not immediately available (screenshot 2).
If I open a client script in a browser using WebSocket, then the response is fixed in an incomprehensible encoding and it is not constant in the text, the only thing you can see on it is only the domain name from which the request came (screenshot 3).
Port: 3000, on 80 and 443, socket not pinged.
Question:
What is the reason for the response from the browser in an incomprehensible encoding and is it necessary to pre-prepare the header text in JS for the handshake? I read on this forum that only the protocol can be optionally specified in WebSocket([url], [protocol]).
Thanks in advance for your advice.
Examples:
Answer:
▒▒▒▒▒2B▒~▒˼[▒▒p'▒w▒
▒%▒▒c▒/ e▒O▒&ߍ▒▒L▒}▒▒4▒▒W▒▒▒4▒▒.▒▒ ▒▒̨̩▒+▒/▒,▒0▒▒▒▒/5▒▒▒domain.name▒
▒▒
# 3+)/▒ ▒~l▒se▒▒lxk▒aG?i▒i0
;m^eCG▒▒jI-+JJ
ih2**▒
============================
Server code:
<?php
// set some variables
$url_site = 'domain.name';
$host = gethostbyname($url_site);
$port = getservbyname('https', 'tcp');
$port = 3000;
// don't timeout!
set_time_limit(0);
$flag_handshake = false;
$client = null;
header("Content-Type:application/javascript; charset=utf-8");
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
echo serialize($socket)." socket_create...\n\n";
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
echo serialize($socket)." socket_bind...\n\n";
// start listening for connections
$result = socket_listen($socket, 0) or die("Could not set up socket listener\n");
echo serialize($socket)." socket_listen...\n\n";
echo "Ready to receive on wss://$host:$port/ ...\n";
do {
if (!$client) {
// accept incoming connections
// client another socket to handle communication
$client = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Client << $client >> has connected.\n";
}
$bytes = #socket_recv($client, $data, 2048, 0);
if ($flag_handshake == false) {
if ((int)$bytes == 0)
continue;
print("Handshaking headers from client: ". mb_detect_encoding($data) ." - ". $data ."\n");
echo $client ." -->>LEN<<-- ". $bytes;
if (handshake($client, $data, $socket)) {
$flag_handshake = true;
}
}
elseif($flag_handshake == true) {
if ($data != "") {
$decoded_data = unmask($data);
print("< ". $decoded_data ."\n");
$response = strrev($decoded_data);
socket_write($client, encode($response));
print("> ". $response ."\n");
socket_close($client);
$client = null;
$flag_handshake = false;
}
}
} while (true);
// close sockets
socket_close($client);
socket_close($socket);
function handshake($client, $headers, $socket) {
print(" [ HEADER: " . $headers ." ] ");
if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match)) {
$version = $match[1];
//$version = 333;
} else {
print(" [ The client doesn't support WebSocket ] ");
return false;
//$version = 111;
}
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) {
$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;
}
?>
============================
Client code:
<html>
<head>
<meta charset="UTF-8">
</head>
<script>
var socket = new WebSocket('wss://domain.name:3000/');
console.log('New socket ');
console.log(socket);
console.log('Let`s open ');
// Open the socket
socket.onopen = function(event) {
console.log(event);
var msg = 'I am the client.';
console.log('> ' + msg);
// Send an initial message
socket.send(msg);
// Listen for messages
socket.onmessage = function(event) {
console.log('< ' + event.data);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};
// To close the socket....
socket.close()
};
socket.onmessage = function(event) {
console.log(`[message] Data received from server: ${event.data}`);
};
socket.onclose = function(event) {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.log('[close] Connection died');
}
};
socket.onerror = function(error) {
console.log(`[error] ${error.message}`);
};
</script>
<body>
<p>Please check the console log of your browser.</p>
</body>
</html>
============================
Sockets seem complex. I just found https://github.com/ghedipunk/PHP-Websockets written in 2012 and got it to work with PHP 8.1 this week.
It seems to work well. Though I haven't really used it to send and receive yet other than tests. Was planning to have the login open a socket and wait for the email confirmation. I even built a way to check the processes for www-data and shell_exec(PHP -q the socket.phpsee img below) to keep the socket open)
May the holy force be with you!

Unpack Javascript with PHP

I need a way to unpack JavaScript with PHP the changing code is on my domain here http://beastfeeds.com/ty9.php the full code is in page source view-source:http://beastfeeds.com/ty9.php for some odd reason the webpage only displays part of the code but the full one is there! I just need it to run and decrypt the code so it displays the decrypted code so i can grab the m3u8 from the output as it changes on every page load. Here is what i am trying to run to achieve it which works fine with Javascript Eval (U.n.p.a.c.k.e.d) but not with this format
<?php
class JavaScriptUnpacker
{
private $unbaser;
private $payload;
private $symtab;
private $radix;
private $count;
function Detect($source)
{
$source = preg_replace("/ /","",$source);
preg_match("/eval\(function\(p,a,c,k,e,[r|d]?/", $source, $res);
Debug::Write($res,"detection result");
return (count($res) > 0);
}
function Unpack($source)
{
preg_match_all("/}\('(.*)', *(\d+), *(\d+), *'(.*?)'\.split\('\|'\)/",$source,$out);
Debug::Write($out,"DOTALL", false);
// Payload
$this->payload = $out[1][0];
Debug::Write($this->payload,"payload");
// Words
$this->symtab = preg_split("/\|/",$out[4][0]);
Debug::Write($this->symtab,"symtab");
// Radix
$this->radix = (int)$out[2][0];
Debug::Write($this->radix,"radix");
// Words Count
$this->count = (int)$out[3][0];
Debug::Write($this->count,"count");
if( $this->count != count($this->symtab)) return; // Malformed p.a.c.k.e.r symtab !
//ToDo: Try catch
$this->unbaser = new Unbaser($this->radix);
$result = preg_replace_callback(
'/\b\w+\b/',
array($this, 'Lookup')
,
$this->payload
);
$result = str_replace('\\', '', $result);
Debug::Write($result);
$this->ReplaceStrings($result);
return $result;
}
function Lookup($matches)
{
$word = $matches[0];
$ub = $this->symtab[$this->unbaser->Unbase($word)];
$ret = !empty($ub) ? $ub : $word;
return $ret;
}
function ReplaceStrings($source)
{
preg_match_all("/var *(_\w+)\=\[\"(.*?)\"\];/",$source,$out);
Debug::Write($out);
}
}
class Unbaser
{
private $base;
private $dict;
private $selector = 52;
private $ALPHABET = array(
52 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP',
54 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR',
62 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
95 => ' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
);
function __construct($base)
{
$this->base = $base;
if($this->base > 62) $this->selector = 95;
else if($this->base > 54) $this->selector = 62;
else if($this->base > 52) $this->selector = 54;
}
function Unbase($val)
{
if( 2 <= $this->base && $this->base <= 36)
{
return intval($val,$this->base);
}else{
if(!isset($this->dict)){
$this->dict = array_flip(str_split($this->ALPHABET[$this->selector]));
}
$ret = 0;
$valArray = array_reverse(str_split($val));
for($i = 0; $i < count($valArray) ; $i++)
{
$cipher = $valArray[$i];
$ret += pow($this->base, $i) * $this->dict[$cipher];
}
return $ret;
// UnbaseExtended($x, $base)
}
}
}
class Debug
{
public static $debug = false;
public static function Write($data, $header = "", $mDebug = true)
{
if(!self::$debug || !$mDebug) return;
if(!empty($header))
echo "<h4>".$header."</h4>";
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
// FOLLOW ALL REDIRECTS:
// This makes multiple requests, following each redirect until it reaches the
// final destination.
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target;
return false;
}
function getURL($u){
$ops = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: text/html\r\n" .
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n"
)
);
$co = stream_context_create($ops);
$r = file_get_contents('http://' . $u, false, $co);
return $r != false ? $r : "";
}
function GetStringBetween($string, $start, $finish){
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}
$grab = file_get_contents("http://beastfeeds.com/ty9.php");
$streama = GetStringBetween($grab, 'var', '</script>');
$unpacker = new JavaScriptUnpacker();
$unpacked = $unpacker->Unpack($grab);
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i', $unpacked, $result, PREG_PATTERN_ORDER);
$result = $result[0];
$stream = GetStringBetween($unpacked, "src:'", "'");
?>
<?= trim($unpacked, "\r\n\t ")?>
I reallllllly need this!!!! any help is greatly appreciated i have been trying to do this for a week now.

JSON_encode not outputting anything

I want to send a query result from one php file to my javascript, I've used an AJAX which seems to work as it is getting data from my BaseClass.php. However when using JSON_encode, it is not outputting anything at all. So I can't work out how to send a query result from one php file(MySQLDao.php) to my BaseClass.php so I am then able to send it to my Javascript file.
My Code:
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode("param" .$param);
echo json_encode("body" .$body);
echo json_encode("recieved" .$recieved);
echo json_encode("result" .$result);
exit();
}
?>
output for the above echo statements:
"paramgetResults""body""recieved""result"
MySQLDao.php - this file holds the query result that I want to pass to my js
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
// echo($obj);
// return $obj;
//}
echo json_encode($result);
//echo($result);
//return false;
}
}
?>
My AJAX code in my js file:
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
Any help is appreciated thanks!

Why does a Javascript function, issued from PHP not found?

I am perplexed. I have done this before and know this should work but cannot understand why the function is not found. Perhaps a second set of eyes will uncover the mystery.
I have tested its existence using JavaScript. See the console log below.
PHP (skip to the end to see statement).
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once "dbconnect.php";
$uploadDirectory = '/home/deje/public_html/writers-tryst/uploads/'; //specify upload directory ends with / (slash)
require_once "dbconnect.php";
$result = 0;
$File_Name = basename($_FILES['file2upload']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name
$target_path = $uploadDirectory . $NewFileName;
if (#move_uploaded_file($_FILES['file2upload']['tmp_name'], $target_path)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $uploadDirectory . $NewFileName);
finfo_close($finfo);
if ($mime_type != 'application/pdf') {
unlink($UploadDirectory . $NewFileName);
$data = array('File MUST be a PDF!');
$result = 0;
} else $result = 1;
}
if (!isset($_REQUEST["title"]) || empty(trim($_REQUEST["title"])))
throw new Exception('You must enter a title.');
else {
$title = filter_var(trim($_REQUEST["title"]), FILTER_SANITIZE_STRING);
$title = htmlspecialchars_decode($title, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || empty(trim($_REQUEST["userid"])))
throw new Exception('Userid is missing.');
else {
$userid = filter_var(trim($_REQUEST["userid"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userid, ENT_QUOTES);
}
if (!isset($_REQUEST["work-type"]) || empty(trim($_REQUEST["work-type"])))
throw new Exception('You must enter a work type.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
if (!isset($_REQUEST["genre"]) || empty(trim($_REQUEST["genre"])))
throw new Exception('You must enter a title.');
else {
$genre = filter_var(trim($_REQUEST["genre"]), FILTER_SANITIZE_STRING);
$genre = htmlspecialchars_decode($genre, ENT_QUOTES);
}
if (!isset($_REQUEST["subgenre"]) || empty(trim($_REQUEST["subgenre"])))
throw new Exception('You must enter a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["subgenre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
if (!isset($_REQUEST["nbrPages"]) || empty(trim($_REQUEST["nbrPages"])))
throw new Exception('You must enter the number of pages your work contains.');
else {
$nbrPages = filter_var(trim($_REQUEST["nbrPages"]), FILTER_SANITIZE_STRING);
$nbrPages = htmlspecialchars_decode($nbrPages, ENT_QUOTES);
}
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare(
"INSERT Writers(fkAccounts, Title, WorkType, Genre, SubGenre, Filename)
VALUES(:fk, :title, :worktype, :genre, :subgenre, :filename)"
);
$stmt->bindParam(':fk', $userid, PDO::PARAM_INT, 10);
$stmt->bindParam(':title', $title, PDO::PARAM_STR, 255);
$stmt->bindParam(':worktype', $worktype, PDO::PARAM_STR, 30);
$stmt->bindParam(':genre', $genre, PDO::PARAM_STR, 100);
$stmt->bindParam(':subgenre', $subgenre, PDO::PARAM_STR, 100);
$stmt->bindParam(':filename', $NewFileName, PDO::PARAM_STR, 30);
$stmt->execute();
//echo "<script type='text/javascript'>stopUpload(" . $result . ");</script>";
?>
<script type='text/javascript'>stopUpload(1);</script>;
JS
function startUpload() {
console.log("stopUpload=" + stopUpload)
$("#userid").val(window.localStorage.getItem('user-id'));
showMessage(1, "Uploading...");
return true;
}
function stopUpload (success) {
var result = '';
if (success == 1) {
showMessage(1, "File uploaded successfully");
}
else {
showMessage(0, 'There was an error uploading the file.');
}
return true;
}
console log
stopUpload=function stopUpload(success) {
var result = '';
if (success == 1) {
showMessage(1, "File uploaded successfully");
}
else {
showMessage(0, 'There was an error uploading the file.');
}
return true; } writers.php:1 Uncaught ReferenceError: stopUpload is not defined(anonymous function) # writers.php:1
EDIT:
Please note the commented within the PHP code. That does not work either.
You are calling the function:
<script type='text/javascript'>stopUpload(1);</script>
But before you call it you need to load your JS:
<script src='./pathto/something.js'></script>; <!-- something.js declares stopUpload -->
<script type='text/javascript'>stopUpload(1);</script>

If websocket handshake completes successfully should I see an onopen event in my client?

First if you could tell me if there is something here that is wrong :
client:
var ws = new WebSocket('ws://localhost:9090/websocket_server.php');// ws://echo.websocket.org/echo
console.log(ws);
ws.onopen = function(e) {
console.log("Connection open...", e);
ws.send("Hello WebSocket!");
};
ws.onmessage = function(e) {
if(typeof e.data === "string"){
console.log("String message received", e, e.data);
} else {
console.log("Other message received", e, e.data);
}
};
ws.onerror = function(e) {
console.log("WebSocket Error: " , e);
};
ws.onclose = function(e) {
console.log("Connection closed", e);
};
server:
<?php
defined('KEY_SUFFIX') ? null : define('KEY_SUFFIX', "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, 'localhost', 9090);
socket_listen($sock);
while (true) {
$client = socket_accept($sock) or die('socket_accept returned false');;
//$buf = socket_read($client, 1024);
$buf = null;$key=null;
while ( $line = socket_read($client, 2048, PHP_NORMAL_READ) ) {
$buf .= $line;
if ( strpos($line, 'Sec-WebSocket-Key')!== false ) {
$key = substr($line, 19);
} else
if ( strpos($line, 'User-Agent')!== false ) {
break;
}
}
//echo $buf;
$sha1 = SHA1($key.KEY_SUFFIX, true);
$accept = base64_encode($sha1);
$write = "HTTP/1.1 101 Switching Protocols\n";
$write .= "Upgrade: websocket\n";
$write .= "connection: Upgrade\n";
$write .= "Sec-Websocket-Accept: $accept\n";
//$write .= "Sec-Websocket-Extensions: extension\n";
socket_write( $client, $write, strlen($write) );
}
socket_close($sock);
?>
I run the php script in this way:
F:\xampp\php\php -q D:\websocket_server.php
Question:
Suppose if It's all correct, I keep looking at chrome debugger network section and It's pending and I expected that after this process I should see an onopen event in js console,
what is going on? Am I expecting wrong?
Should the connection between sever and client go from 0 state to 1 state after this process or It needs more work to establish an open state?
I found the problems:
mistakes:
1: reading the last character in the line of the sec-websocket-key which made the calculation of the sec-websocket-accpet wrong on line 18
2: Didn't know 2 things about response header : one is that you need to put \r\n at the end of each line not just \n and seccond is that you need to put two \r\n\r\n after the last line of header, it just doesn't work if it's not two. (lines: 30-33)
Now it initiates an onopen event in client.
<?php
defined('KEY_SUFFIX') ? null : define('KEY_SUFFIX', "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, 'localhost', 9090);
socket_listen($sock);
while (true) {
$client = socket_accept($sock) or die('socket_accept returned false');;
//$buf = socket_read($client, 1024);
$buf = null;$key=null;
while ( $line = socket_read($client, 2048, PHP_NORMAL_READ) ) {
$buf .= $line;
if ( strpos($line, 'Sec-WebSocket-Key')!== false ) {
$key = substr($line, 19, 24); // <== mistake num 1 here
} else
if ( strpos($line, 'User-Agent')!== false ) {
break;
}
}
//echo $buf;
$sha1 = SHA1($key.KEY_SUFFIX, true);
$accept = base64_encode($sha1);
//mistake num 2 here
$write = "HTTP/1.1 101 Switching Protocols\r\n";
$write .= "Upgrade: websocket\r\n";
$write .= "connection: Upgrade\r\n";
$write .= "Sec-Websocket-Accept: $accept\r\n\r\n";
socket_write( $client, $write, strlen($write) );
}
socket_close($sock);
?>

Categories

Resources