【发布时间】:2010-07-25 04:26:23
【问题描述】:
嘿,我正在尝试在 php 中创建数据输出流 将原始数据类型写回 Java 应用程序
我创建了一个将数据写入数组的类 (和java一样写,从java代码复制)
最后我将数组写回客户端。
感觉不太好
例如 writeInt 方法 向 java 客户端发送一些错误的值 我还好吗?
谢谢你
这是我的代码
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;
}
这就是我设置主 php 文件的方式
header("Content-type: application/octet-stream" ,true);
header("Content-Transfer-Encoding: binary" ,true);
这就是我返回数据的方式
$arrResult = $dataOutputStream->toByteArray();
for ($i = 0 ; $i < count($arrResult) ; $i ++){
echo $arrResult[$i];
}
我根据我的代码更改编辑问题 在Java客户端似乎我总是有2个字节要读取开始 我有 13 , 10 ,即 \r \n 我怎么老是看书?
(在我的测试中,我向 java 客户端发送一个字节,
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++) {
read = 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)
【问题讨论】:
-
您采用这种方式而不是使用中间数据传输(如 JSON、WDDX 或普通的旧 XML)是否有特殊原因?
-
是的,我有一个网络协议机制,我和朋友很久以前用 java 实现了,我更喜欢这个协议
-
知道了很奇怪....我让我的示例工作我写了 3 个不同的 int 值,它看起来很好我必须做的是忽略我正在阅读的前 2 个字节,可以吗?一帮我为什么?我现在更新关于我如何发送字节的帖子
标签: java php outputstream