PHP socket connects to the server template, socket server. When the socket of PHP is connected to the server template, the socket server finds that some cached data needs to be accessed by external interfaces while organizing the new framework. What is more convenient is the php interface, PHP socket connection to the server template, socket server
When sorting out the new framework, I found that some cached data needs to be accessed through external interfaces, which is more convenient for php interfaces. so I temporarily studied how php connects to the java server.
First paste the code:
require_once 'CRC16.php';
/*-----------------------------
| Send data packets to the server
------------------------------*/
classServer{
// Send data packets
publicstaticfunction sendPacket($packet, $host, $port){
$protocol ='tcp';
$get_prot = getprotobyname ( $protocol );
// Create a socket
$socket = socket_create ( AF_INET, SOCK_STREAM, $get_prot );
// Establish a connection
$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);
// Wait for acceptance
$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;
}
// Write two bytes of data
privatestaticfunction writeShort($s){
return pack ("n", $s );
}
// Write 4 bytes of data
privatestaticfunction writeInt($N){
return pack ("N", $N );
}
// Write 1 byte of data
privatestaticfunction writeByte($b){
return pack ("c", $b );
}
}
After a personal server is connected, a crcCode verification code will be assigned, and the sent message needs to be encrypted with crc16 (in fact, it is very easy to keep a bit mysterious), so wait for a fixed length to get the crcCode, after sending the request, wait for receiving the data packet and return it.
From Weizhi note (Wiz)
How does PHP Socket communicate with the client?
The server provides a data buffer and a user identification mechanism. To send the corresponding information to the chat user.
It seems that the communication between the user and the user is essentially the communication between the user and the server.
My understanding
Php socket connection failure
Check the port
While organizing the new framework, the hacker finds that some cached data needs to be accessed by external interfaces, while the php interface is more convenient ,...