The socket of PHP is connected to the service-side template, the socket server
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 = ( 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 );
}
}
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)
How does a PHP socket communicate with the client on the server?
The server provides a data buffer and provides a mechanism for user identification. This is to send the corresponding information to both users of the chat.
It appears that the communication between the user and the user is essentially the user communicating with the server.
My point of understanding
The PHP socket is not connected
Check the port.
http://www.bkjia.com/PHPjc/880092.html www.bkjia.com true http://www.bkjia.com/PHPjc/880092.html techarticle PHP Socket connection to the service-side template, the socket server in the new framework, the discovery of some cached data, the need for external interface access, and more convenient is the PHP interface, ...