1

I have a simple server that streams binary data (0 and 1) via tcp on a port.
I want to use php and read that binary data (bits), store it in a string and display it in the browser and later decode it my way.
I don't want to read whole TCP packet with the head, just the data in the packet.

Here is the code I managed to produce in this time, when running it in browser, it succesfully connects to server and the server sends data. The data is received, but displayed in some strange russian letters.

<?php
// host and port to connect to
$host = "127.0.0.1";
$port = 1991;

// connect to the port
$fp = fsockopen($host, $port, $errno, $errstr);

// don't die
set_time_limit(0);

// if connection not successfull, display error
if (!$fp)
{
    die("Error: Could not open socket for connection!");
}
else
{
    // connection successfull, listen for data (1024 bytes by default)
    $got = fgets($fp);

    // display the data
    echo $got;
}

fclose($fp);

?>
<br><br><br><br>
Server closed;

I want to display the received bits in a string. For further decoding I need bytes made out of 8 bits. But I have no idea how to accomplish this.
Thank you for your help.

1 Answer 1

2

Actually you don't need to parse the TCP header since PHP will do it for you. With fgets() you will get only the payload. This payload is composed by one or several bytes.

In order to get each bit from each byte of this payload, you'll have to use the bitwise operators.

I suggest you to use socket_read() instead of fgets(), which is not reliable with binary data:

$got = socket_read($fp, 1024);

$got contains all your bytes that you can get with this kind of loop:

for ($i = 0; $i < strlen($got); ++$i)
{
    echo $got[$i]; // print one byte
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.