在整理新框架的時候,發現對於一些緩存數據,需要對外的接口訪問,而比較方便的是php的接口,所以臨時研究了下php如何連接java服務端。
先貼上代碼:<?php
require_once 'CRC16.php';
/*-----------------------------
| 向服務器發送數據包
------------------------------*/
classServer{
//發送數據包
publicstaticfunction sendPacket($packet, $host, $port){
$protocol ='tcp';
$get_prot = getprotobyname ( $protocol );
//創建socket
$socket = socket_create ( AF_INET, SOCK_STREAM, $get_prot );
//建立連接
$conn = socket_connect ( $socket, $host, $port );
if(!$conn){
socket_close($socket);
exit("socket connect failed!");
}
$buffer =@socket_read($socket,9, PHP_NORMAL_READ);
$crcCode =(ord($buffer[7])<<8)+ord($buffer[8]);
$len = strlen($packet);
$newpacket = CRC16::encode($packet, $crcCode,4);
socket_send ( $socket, $newpacket, $len,0);
//等待接受
$head =@socket_read($socket,4,PHP_NORMAL_READ);
$len =(ord($head[0])<<24)+(ord($head[1])<<16)+(ord($head[2])<<8)+ord($head[3]);
$content =@socket_read($socket,$len-4,PHP_NORMAL_READ);
socket_close ( $socket );
return substr($content,3);
}
publicstaticfunction packet($group,$cmd,$message){
$size = strlen($message)+8;
$str ='';
$str .=self::writeInt($size);
$str .=self::writeByte(0);
$str .=self::writeByte($group);
$str .=self::writeByte($cmd);
$str .=self::writeByte(1);
$str .= $message;
return $str;
}
//寫進2個byte的數據
privatestaticfunction writeShort($s){
return pack ("n", $s );
}
//寫進4個byte的數據
privatestaticfunction writeInt($N){
return pack ("N", $N );
}
//寫進1個byte的數據
privatestaticfunction writeByte($b){
return pack ("c", $b );
}
}
服務器提供數據緩沖區,並提供一種用戶識別機制。以此來給聊天用戶雙方發送相應的信息。
看似用戶與用戶之間的通信實質上是用戶在與服務器通信。
我的一點理解
查一下端口把