最近看了一一個(gè)PHP SOCKET服務(wù)端代碼,對(duì)于其中對(duì)SOKET協(xié)議的數(shù)據(jù)解析部分看不明白,就是以下代碼中的uncode方法;希望知道的牛人解答下,謝謝!附件中有相關(guān)客戶端和服務(wù)端代碼!
function uncode($str,$key){
$mask = array();
$data = '';
$msg = unpack('H*',$str);
// print_r($msg); echo "\r\n";
$head = substr($msg,0,2);
if ($head == '81' && !isset($this->slen)) {
$len=substr($msg,2,2);
$len=hexdec($len);
if(substr($msg,2,2)=='fe'){
$len=substr($msg,4,4);
$len=hexdec($len);
$msg=substr($msg,4);
}else if(substr($msg,2,2)=='ff'){
$len=substr($msg,4,16);
$len=hexdec($len);
$msg=substr($msg,16);
}
$mask[] = hexdec(substr($msg,4,2));
$mask[] = hexdec(substr($msg,6,2));
$mask[] = hexdec(substr($msg,8,2));
$mask[] = hexdec(substr($msg,10,2));
$s = 12;
$n=0;
}else if($this->slen > 0){
$len=$this->slen;
$mask=$this->ar;
$n=$this->n;
$s = 0;
}
$e = strlen($msg)-2;
for ($i=$s; $i<= $e; $i+= 2) {
$data .= chr($mask^hexdec(substr($msg,$i,2)));
$n++;
}
$dlen=strlen($data);
if($len > 255 && $len > $dlen+intval($this->sjen)){
$this->ar=$mask;
$this->slen=$len;
$this->sjen=$dlen+intval($this->sjen);
$this->sda=$this->sda.$data;
$this->n=$n;
return false;
}else{
unset($this->ar,$this->slen,$this->sjen,$this->n);
$data=$this->sda.$data;
unset($this->sda);
return $data;
}
}
看樣子這個(gè)協(xié)議不是websocket的協(xié)議,
沒有必要去完全理解別人的協(xié)議,有時(shí)只有協(xié)議的制定者才能知道如果解析這個(gè)協(xié)議。
首先這個(gè)協(xié)議是用16進(jìn)制明文傳遞的
使用$msg = unpack('H*',$str); 轉(zhuǎn)換成了原始請(qǐng)求數(shù)據(jù)
首部?jī)蓚€(gè)字節(jié)是head,存儲(chǔ)的應(yīng)該是一個(gè)short int型數(shù)字,第三到第四字節(jié)也是一個(gè)short int,存儲(chǔ)的是包長(zhǎng),下面的如果包長(zhǎng)為ff或者fe分別有不同的解法....