PHP的socket连接到服务端模版

在整理新框架的时候,发现对于一些缓存数据,需要对外的接口访问,而比较方便的是php的接口,所以临时研究了下php如何连接java服务端。

先贴上代码:
  1. <?php
    
    require_once 'CRC16.php';
    
    /*-----------------------------
    
     | 向服务器发送数据包
    
     ------------------------------*/
    
    
    
    class Server {
    
    	//发送数据包
    
    	public static function 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);
    
    	}
    
    	
    
    	public static function 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的数据
    
    	private static function writeShort($s) {
    
    		return pack ( "n", $s );
    
    	}
    
    	//写进4个byte的数据
    
    	private static function writeInt($N) {
    
    		return pack ( "N", $N );
    
    	}
    
    	//写进1个byte的数据
    
    	private static function writeByte($b) {
    
    		return pack ( "c", $b );
    
    	}
    
    }
    
    

      


因为个人服务端连接之后,会分配一个crcCode校验码,发送的消息需要进行crc16的加密(其实很简单的,保持点神秘感),所以先等待接受固定长度来获得crcCode,然后发送请求后,等待接受数据包,并返回。





你可能感兴趣的:(socket)