PHP fwirte() how can I set timeout? - php

I have a problem.
I connect a server use fsockopen and it success.
Maybe Network blocking after connect successed, so, I want to set a timeout when I use fread and fwrite.
I can set timeout with stream_set_timeout when I fread something,
and checked by stream_get_meta_data.
$fs = fsockopen("127.0.0.1", 10008, $errno, $errstr, 1);
stream_set_timeout($fs, 5, 0);
read(1024,$fs);
function read($length, $fs)
{
$read = 0;
$parts = array();
while ($read < $length && !feof($fs)) {
$data = fread($fs, $length - $read);
$status = stream_get_meta_data($fs);
if ($status['timed_out']) {
die("Stream Timeout!n");
}
$read += strlen($data);
$parts []= $data;
}
return implode($parts);
}
now, I want to know, if stream_set_timeout can work in fwrite?
and, How can I set timeout when I use fwrite?
My English is so poor.sorry.

Related

PHP Websocket server - Handle more frames in socket_recv

Hope this wasn't solved here before, but I was really trying to look for answer!
I Have a problem with receiving frames via socket_recv in PHP server. Problem appears when I send more than 1 messages from client in one time (e.g. in cycle). By the stream length it's match frames count but I'm not able to unmask frames correctly and my unmask function return only first frame. I'm using part of php server I found here and for one message it's working properly, but when I receive more messages at time, it don't unmask all.
I tryed to add loop to go thru all frames, but I'm not able to find end of frame and continue to other.
Here is main while of server:
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 10240); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type' => 'system', 'status' => true, "id" => "SRV_CONNECTED", 'message' => $ip . ' connected'))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
foreach ($changed as $changed_socket) {
while (#socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text, true); //json decode
$response_text = parse_msg($tst_msg, $changed_socket);
break 2; //exit this loop
}
$buf = #socket_read($changed_socket, 10240, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected')));
send_message($response);
}
}
I Need to call parse_msg by count of frames received in #socket_recv which should be returned by unmask function.
And here is unmask function:
function unmask($payload){
$decMessages = Array();
do { // This should be running until all frames are unmasked and added to $decMessages Array
$length = ord($payload[1]) & 127;
if($length == 126) {
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
$len = (ord($payload[2]) << 8) + ord($payload[3]);
}elseif($length == 127) {
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
$len = (ord($payload[2]) << 56) + (ord($payload[3]) << 48) +
(ord($payload[4]) << 40) + (ord($payload[5]) << 32) +
(ord($payload[6]) << 24) +(ord($payload[7]) << 16) +
(ord($payload[8]) << 8) + ord($payload[9]);
}else {
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
$len = $length;
}
$text = '';
for ($i = 0; $i < $len; ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
$decMessages[] = $text;
// Here is problem. It doesn't put correct substr to $payload, so it could run again on stream shorted by last message
$payload = substr($payload, $length, strlen($payload));
}while (($len < strlen($data)) and $countert < 10);
return $decMessages;
}
I think my problem is here: $payload = substr($payload, $length, strlen($payload)); Where I'm putting wrongly rest of stream?
So my questions are:
Why #socket_recv return more than one frame
How can i change my unmask function to go thru all frames, not just a first one
I will be extremelly greatfull for any help, because I'm fighting with this more than I should.
Thanks in advance
Klara!
so, I found solution for this. As I thought, problem was multiple frames in one receive. I needed to edit my unmask function to check if there are still frames in stream.
Basically, what I had was right but $length in
$payload = substr($payload, $length, strlen($payload));
was wrong. Instead of $length I used $len + 8, 14 od 6 depend on $length. I'm not sure how to describe why this but I'm sure somebody will. That's all. Now it's working as it should!
Thanks!

Cannot get required headers from some IPs and ports to parse song title using ShoutCast protocol

I'm trying to extract song title from live mp3 streams using SC protocol. The php script works fine with some IPs and ports, however with some IPs and ports I cannot get required headers from the response to determine the meta-block frequency, therefore I cannot find the location of the song title in the stream. Here's my code:
<?php
while(true)
{
//close warning messages (re-open for debugging)
error_reporting(E_ERROR | E_PARSE);
//create and connect socket with the parameters entered by the user
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
echo "Establishing connection to the given adress...\n";
$fp = fsockopen($argv[1], $argv[2], $errno, $errstr, 10);
if($fp)
{
echo "Connection established.\n";
$result = socket_connect($sock, $argv[1], $argv[2]);
//prepare request
$request = "GET / HTTP/1.1\r\n";
$request .= "Icy-MetaData: 1\r\n\r\n";
//send request
socket_write($sock,$request,strlen($request));
//set sentinel boolean value's initial value
$headers = true;
//put the segment to be parsed into a string variable
$l = socket_read($sock,2048);
$meta = "";
$streamurl = "";
$checkContentType = false;
//Parsing metadata frequency and streamurl from response's headers.
foreach(preg_split("/((\r?\n)|(\r\n?))/", $l) as $line)
{
if(!(strpos($line, "metaint:") === false))
{
$meta = $line;
}
if(!(strpos($line, "icy-url:") === false))
{
$streamurl = $line;
}
if(!strpos($line, "audio/mpeg") === false)
{
$checkContentType = true;
}
}
echo $l;
//Checking if the content of the stream is mpeg or not
if($checkContentType)
{
$pos = strpos($meta, ":");
$interval = intval(substr($meta,$pos+1));
$pos = strpos($streamurl, ":");
$streamurl = substr($streamurl, $pos+1);
$flag = false;
//initialize bytecount to 0
$bytecount = 0;
//Extracting song title using SC protocol
while($headers)
{
$l = socket_read($sock,PHP_NORMAL_READ);
$bytecount++;
if($bytecount == $interval )
{
$headers = false;
$flag = true;
}
if($flag)
{
$len = ord($l);
}
}
//Determining length variable
$len = $len * 16;
$string = socket_read($sock,$len);
$pos2 = strpos($string, "'") + 1;
$pos3 = strpos($string, ";",$pos2) -1;
$songtitle = substr($string, $pos2, ($pos3-$pos2));
//Formatting the log entry
$finalstr = "[".date("c")."]"."[".$streamurl."]".$songtitle."\n";
echo "logged".$finalstr;
//finalize connection
socket_close($sock);
//Writing the requested info to a log file
file_put_contents("log.txt", $finalstr,FILE_APPEND | LOCK_EX);
//waiting 5 minutes
echo "Logging next entry in five minutes. \n";
sleep(300);
}
else
{
echo "Content of the stream is not suitable.\n";
exit;
}
}
else
{
echo "Unable to connect to the given ip and port.\n Exiting...\n";
socket_close($sock);
exit;
}
}
?>
I've never tried to access shoutcast programatically but I've run streaming audio servers in the past. There are actually two different flavours of shoutcast server and I would guess your program is trying to talk to one and these broken servers are the other type.
From the post READING SHOUTCAST METADATA FROM A STREAM:
Turns out that SHOUTcast and Icecast (two of the most popular server
applications for streaming radio) are supposed to be compatible, but
the response message from each server is slightly different.
Full details about the shoutcast protocol: Shoutcast Metadata Protocol

PHP - TCP/IP fsockopen

I was wondering if anyone has had any experience with this before. I'm trying to write a simple script that will continously read data from the TCP/IP stream but for some reason or another the script reads in a bunch of data, writes it out and then just stops.
$fp = fsockopen("xxxx", 3000, $errno, $errstr, 5);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
while (!feof($fp)) {
echo fgets($fp, 128)."\n";
fflush($fp);
}
fclose($fp);
}
I'd like it to have a constant flow to it, rather then echo out a bunch of data then wait 30 seconds and output a bunch more data. Anyone have any ideas?
---- EDIT ----
ZMQ Code
include 'zmsg.php';
$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_DEALER);
// Generate printable identity for the client
$identity = sprintf ("%04X", rand(0, 0x10000));
$client->setSockOpt(ZMQ::SOCKOPT_IDENTITY, $identity);
$client->connect("tcp://xxxx:3000");
$read = $write = array();
$poll = new ZMQPoll();
$poll->add($client, ZMQ::POLL_IN);
$request_nbr = 0;
while (true) {
// Tick once per second, pulling in arriving messages
for ($centitick = 0; $centitick < 100; $centitick++) {
$events = $poll->poll($read, $write, 1000);
$zmsg = new Zmsg($client);
if ($events) {
$zmsg->recv();
echo $zmsg->body()."\n";
//printf ("%s: %s%s", $identity, $zmsg->body(), PHP_EOL);
}
}
$zmsg = new Zmsg($client);
//$zmsg->body_fmt("request #%d", ++$request_nbr)->send();
}
Here is how you connect to a server (as a client) if your goal is ONLY to PULL data (read).
<?php
$context = new ZMQContext();
$sock = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$sock->connect("tcp://ADDRESS:3000");
while (true)
{
$request = $sock->recv(); # recv is blocking by default, no need to put timers.
printf ("Received: %s;%s", $request, PHP_EOL);
}
?>
if you want to reply, you'll need to use a pair socket (ZMQ::SOCKET_PAIR), then you can use:
$sock->send("data to send");
Also, if instead of you connecting to clients, clients connects to you, use the bind method instead of connect.
EDIT: use the PUSH socket type on the other side if you use the pull here, else, use the pair socket on both sides.

PHP Socket - send binary data

How to send binary data representing 01 (PHP)?
My Server code (sockets TCP, address is only example. I use my server address of course)
error_reporting(E_ALL);
set_time_limit(0);
ignore_user_abort(true);
$address = '11.111.111.111'; // example server address
$port = 9000; // example port
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, $address, $port);
socket_listen($sock);
$clients = array($sock);
while(true) {
$read = $clients;
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1) {
continue;
}
if (in_array($sock, $read)) {
$clients[] = $newsock = socket_accept($sock);
$key = array_search($sock, $read);
unset($read[$key]);
}
foreach ($read as $read_sock) {
$data = #socket_read($read_sock, 1024);
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
unset($clients[$key]);
echo "client disconnected.\n";
// continue to the next client to read from, if any
continue;
}
$data = trim($data);
// check if there is any data after trimming off the spaces
if (!empty($data)) {
// send this to all the clients in the $clients array (except the first one, which is a listening socket)
foreach ($clients as $send_sock) {
// if its the listening sock or the client that we got the message from, go to the next one in the list
if ($send_sock == $sock || $send_sock == $read_sock) {
continue;
}
$fp = fopen('socket_communication.txt', 'a');
fwrite($fp, date("Y-m-d H:i:s")." - DATA ".$data."\n");
fclose($fp);
$value = unpack('H*', "1");
$response = base_convert($value[1], 16, 2);
socket_write($send_sock, $response, 1);
} // end of broadcast foreach
}
}
}
echo "Closing sockets...";
socket_close($sock);
I would like to server sent binary data (01 or 1).
I use unpack function and convert it by base_convert but it doesnt works.
This code send response to client
$value = unpack('H*', "1");
$response = base_convert($value[1], 16, 2);
socket_write($send_sock, $response, 1);

Are sockets so slow in PHP?

I'm using this code for sockets. Console says that the page is processed for a very small amount of time, but Chrome says that page is loading for ~1 second!
$this->serv_sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($this->serv_sock, $this->serv, $this->port) or die("Could not bind to address\n");
socket_listen($this->serv_sock);
while (1) {
echo "Waiting...\n";
$client = socket_accept($this->serv_sock);
$start_mtime = microtime(true);
echo "Accepted at ".$start_mtime.".\n";
$input = '';
$len = 0;
do {
//echo "Reading.\n";
$inp = socket_read($client, 1024);
$input .= $inp;
if (strpos($input, "\n\n") === false && strpos($input, "\r\n\r\n") === false)
continue;
if (!$len) {
if (!preg_match("/Content-Length: (\d+)/", $input, $matches)) {
break;
}
$len = $matches[1];
if (!$len)
break;
echo "We want $len bytes.\n";
}
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
if (strlen($content) >= $len)
break;
} while ($inp);
echo "Calling callback as ".microtime(true).".\n";
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
$output = $this->translate($callback, $headers, $content); // nothing slow here
$time_end = microtime(true);
echo "Sending output at ".$time_end." (total ".($time_end - $start_mtime).")\n\n";
$output = "HTTP/1.0 Ok\n".
"Content-Type: text/html; charset=utf-8\n".
"Content-Length: ".strlen($output)."\n".
"Connection: close\n\n".
$output;
socket_write($client, $output);
socket_close($client);
}
If I understand what you're saying. As far as I know there is a difference between server processing time and client processing time.
The time it actually takes to process the information on the server will always be less. Once the server finishes processing the information the data still has to be sent to the browser and has to be rendered. The time for the data to get there and for the browser to render is what I'm suspecting the reason is as to why Chrome is telling you it's taking ~1 second.

Categories