function MyFunc($userid, $guid)
{
//固定包头
//包ID = (1053)D = (041D)H
//加密码 = 0
//包Len = 8
$packetHead = "\x1D\x04\x00\x08\x00\x00\x00";
Print($userid);
Print($guid);
//构造包体
//UserID
$param1 = getNetByteStream($userid);
//Guid
$param2 = getNetByteStream($guid);
$packetBody = $param1.$param2;
$address = "192.168.0.108";
$service_port = 9005;
$content = $packetHead.$packetBody;
if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))< 0)
echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
//echo "Attempting to connect to '$address' on port '$service_port'...";
if (($result = socket_connect($socket, $address, $service_port))< 0)
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
$res = socket_write($socket, $content, 15);
socket_close($socket);
}
//得到用于传输的网络字节流
function getNetByteStream($n) {
$array = array(0,0,0,0,0,0,0,0);
$i = 0;
//先转成16进制
$temp = $n;
while ($temp != 0) {
$i++;
$array[8-$i] = $temp%16 ;
$temp = floor($temp/16);
}
//字节倒序
for ($i = 0; $i < 4; $i+=2) {
$t1 = $array[$i];
$t2 = $array[$i+1];
$array[$i] = $array[6-$i];
$array[$i+1] = $array[7-$i];
$array[6-$i] = $t1;
$array[7-$i] = $t2;
}
//再转换回来,生成字节流
$strRet = "";
for ($i = 0; $i < 8; $i += 2) {
$xxx = $array[$i]*16 + $array[$i+1];
$strRet = $strRet.chr($xxx);
}
return $strRet;
}
假设要生成的struct 结构是这样子的,
struct TEST{
char name[10];
char pass[33];
int age;
unsigned char flag;
};
在php中我用类模拟这个结构体
[php]
class struct{
var $name;
var $pass;
var $age;
var $flag;
function __construct($name,$pass,$age,$flag){
$this->name=$name;
$this->pass=$pass;
$this->age=$age;
$this->flag=$flag;
pack("a10",$this->name);
pack("a33",$this->pass);
pack("i*",$this->age);
pack("C*",$this->flag);
settype($this->name,'string');
settype($this->pass,'string');
settype($this->flag,'int');
settype($this->flag,'string');
}
}
$st=new struct();
$st->name="Test";
$st->pass="Test";
$st->age="5";
$st->flag="1";
print_r($st);
[/php]
- $msg = pack("a10",$this->name);
- $msg .= pack("a33",$this->pass);
- $msg .= pack("i*",$this->age);
- $msg .= pack("C*",$this->flag);
- 就是把数据转成二进制,序列,$msg作为包通过socket,发给c++
- 当然如果c++ 回给你的包里面有是结构的,二进制序列,你就得用unpack安之前的顺序来解包
- 不管是c++还是php 发包,都要转成二进制序列, 这个序列的顺序,当然是双方沟通后的结构,也可以是单方定后,告诉另一方.
- 和写文件一样, 不能一下把一个结构体写到文件里吧.一项一项的顺序还是自己定的