网站首页php
socket接口访问数据提交方式
发布时间:2018-11-26 02:36:45编辑:hover阅读(3110)
一、根据接口方提供的socket数据格式, 拼接出要提交的数据串,方式如下:
private function buildSocketData(){ #数据包头部,数据体及尾位拼接时,使用到的几个间隔符 $char31 = chr(31); $char30 = chr(30); $char12 = chr(12); $char13 = chr(13); $main= array( 'FJKSPJBM'=>'410103', 'FSKRH'=>'005', 'FKPRQ'=>date('Y-m-d'), 'FSKQRM'=>rand(1000, 9999), 'FYHWDBM'=>'900001001', 'FYHCZYBM'=>'0001', 'FJSXS'=>'6', ); $detail1 = array( 'FXMBM'=>'424099', 'FBZBM'=>'001', 'FSL'=>$num, 'FJE'=>$amount, ); $header = "90".$char31."0592501".$char31."411800-9000".$char31.date('Y-m-d').$char31."0".$char31."0"; $body = $char30.'90203'.$char12.implode($char31, $main).$char13.implode($char31, $detail1); $tail = chr(30).chr(4); $data = $header.$body.$tail; $data = iconv('utf-8', 'gb18030', $data);//接口方使用的gb18030字符集,需要转码后提交 return $data; }
二、执行数据提交
private function socketSubmit($str){ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//创建并返回套接字 $ret = socket_connect($socket, '127.0.0.1', 1530); //开启套接字连接 if(!$ret){ echo 'socket connect failed.'."\n"; return false; } $length = strlen($str); socket_write($socket, $str, $length); //向打开的套接字写入数据 $result=""; while($data = socket_read($socket, 1024)){ //读取套接字返回的数据包 $result .= $data; } $result= mb_convert_encoding($result, 'utf-8', 'gb18030'); //接收到数据后,重新转回utf-8输出显示 socket_close($socket); echo $result; }
评论