java writeInt from php,
hey all i am trying to make a data output stream in php to write back primitive data types to a java application
i created a class that write the data to an array (write it same as java do , copy from java code)
and finally i am writing back the array to the client.
feels like its not working well
for example the writeInt method send to the java client some wrong values am i doing ok ?
thank you
here is my code
private $buf = array();
public function writeByte($b) {
$this->buf[] = pack('c' ,$b);
}
public function writeInt($v) {
$this->writeByte($this->shiftRight3($v , 24) & 0xFF);
$this->writeByte($this->shiftRight3($v , 16) & 0xFF);
$this->writeByte($this->shiftRight3($v , 8) & 0xFF);
$this->writeByte($this->shiftRight3($v , 0) & 0xFF);
}
private function shiftRight3($a ,$b){
if(is_numeric($a) && $a < 0){
return ($a >> $b) + (2<<~$b);
}else{
return ($a >> $b);
}
}
public function toByteArray(){
return $this->buf;
}
this is how i am setting the main php file
header("Content-type: application/octet-stream" ,true);
header("Content-Transfer-Encoding: binary" ,true);
this is how i am returning the data
$arrResult = $dataOutputStream->toByteArray();
for ($i = 0 ; $i < count($arrResult) ; $i ++){
echo $arrResult[$i];
}
I EDIT THE QUESTION ,ACCOURDING TO MY CODE CHANGING in the java client side seems that i have 2 bytes to read start always i have 13 , 10 , which is \r \n how come i am reading them always ?
(in my test i am sending one byte to the java client side ,
URL u = new URL("http://localhost/jtpc/test/inputTest.php");
URLConnection c = u.openConnection();
InputStream in = c.getInputStream();
int read = 0;
for (int j = 0; read != -1 ; j++) {
r开发者_JS百科ead = in.read();
System.out.println("More to read : " + read);
}
)
the output will be ,
More to read : 13
More to read : 10
More to read : 1 (this is the byte i am sending)
Php has pack()
function for turning data into binary form. Unpack()
reverses the operation.
$binaryInt = pack('I', $v);
The one thing that strikes me as odd is that you are setting the content type to application/zip, but you don't seem to be creating a ZIP encoded output stream. Is this an oversight ... or does PHP perform the encoding for you without you asking?
EDIT
According to RFC 2046, the recommended content type for a binary data format whose content type is not standardized is "application/octet-stream". There is also a practice of defining custom content subtypes with a name starting with "x-" (for experimental), but RFC 2046 says that this practice is now strongly discouraged.
You don't need that shiftRight3() method, just use >>, as you are masking the result, and then turning it into a chr(). Throw it away.
精彩评论