PHP的socket连接到服务端模版
在整理新框架的时候,发现对于一些缓存数据,需要对外的接口访问,而比较方便的是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 );
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。