In the new framework, the discovery of some cached data, external interface access, and more convenient is the PHP interface, so the temporary study of the next PHP how to connect to the Java server.
First put the code:
<?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 = ( Span class= "PLN" >ord ( $head [ Span class= "lit" >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 );
}
}
Since the personal server is connected, a Crccode checksum is assigned, and the message sent needs to be CRC16 encrypted (in fact very simple, keeping the dots secret), so wait for a fixed length to get Crccode, then send the request, wait for the packet to be received, and return.
From for notes (Wiz)
PHP socket connection to service-side template