例如,需要发送以下数据

struct header

{

int  type; // 消息类型

int  length; // 消息长度

}

struct MSG_Q2R2DB_PAYRESULT

{

int   serialno;

int   openid;

char payitem[512];

int   billno;

int   zoneid;

int   providetype; 

int   coins;

}

调用的方法,另外需require两个php文件,一个是字节编码类,另外一个socket封装类,其实主要看字节编码类就可以了!

public function index() {
$socketAddr = "127.0.0.1";
$socketPort = "10000";
try { $selfPath = dirname ( __FILE__ );
require ($selfPath . "/../Tool/Bytes.php");
$bytes = new Bytes (); $payitem = "sdfasdfasdfsdfsdfsdfsdfsdfsdf";
$serialno = 1;
$zoneid = 22;
$openid = "CFF47C448D4AA2069361567B6F8299C2"; $billno = 1;
$providetype = 1;
$coins = 1; $headType = 10001;
$headLength = 56 + intval(strlen($payitem )); $headType = $bytes->integerToBytes ( intval ( $headType ) );
$headLength = $bytes->integerToBytes ( intval ( $headLength ) );
$serialno = $bytes->integerToBytes ( intval ( $serialno ) );
$zoneid = $bytes->integerToBytes ( intval ( $zoneid ) );
$openid = $bytes->getBytes( $openid );
$payitem_len = $bytes->integerToBytes ( intval ( strlen($payitem) ) );
$payitem = $bytes->getBytes($payitem);
$billno = $bytes->integerToBytes ( intval ( $billno ) );
$providetype = $bytes->integerToBytes ( intval ( $providetype ) );
$coins = $bytes->integerToBytes ( intval ( $coins ) ); $return_betys = array_merge ($headType , $headLength , $serialno , $zoneid , $openid,$payitem_len ,$payitem,$billno,$providetype,$coins); $msg = $bytes->toStr ($return_betys);
$strLen = strlen($msg); $packet = pack("a{$strLen}", $msg);
$pckLen = strlen($packet); $socket = Socket::singleton ();
$socket->connect ( $socketAddr, $socketPort ); //连服务器
$sockResult = $socket->sendRequest ( $packet); // 将包发送给服务器 sleep ( 3 );
$socket->disconnect (); //关闭链接 } catch ( Exception $e ) {
var_dump($e);
$this->log_error("pay order send to server".$e->getMessage());
}
}

Bytes.php  字节编码类

<?php

/**
* byte数组与字符串转化类
* @author
* Created on 2011-7-15
*/ class Bytes { /**
* 转换一个String字符串为byte数组
* @param $str 需要转换的字符串
* @param $bytes 目标byte数组
* @author Zikie
*/ public static function getBytes($str) { $len = strlen($str);
$bytes = array();
for($i=0;$i<$len;$i++) {
if(ord($str[$i]) >= 128){
$byte = ord($str[$i]) - 256;
}else{
$byte = ord($str[$i]);
}
$bytes[] = $byte ;
}
return $bytes;
} /**
* 将字节数组转化为String类型的数据
* @param $bytes 字节数组
* @param $str 目标字符串
* @return 一个String类型的数据
*/ public static function toStr($bytes) {
$str = '';
foreach($bytes as $ch) {
$str .= chr($ch);
} return $str;
} /**
* 转换一个int为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
* @author Zikie
*/ public static function integerToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff); // >>:移位 &:与位
$byt[2] = ($val >> 16 & 0xff);
$byt[3] = ($val >> 24 & 0xff);
return $byt;
} /**
* 从字节数组中指定的位置读取一个Integer类型的数据
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Integer类型的数据
*/ public static function bytesToInteger($bytes, $position) {
$val = 0;
$val = $bytes[$position + 3] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 2] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 1] & 0xff;
$val <<= 8;
$val |= $bytes[$position] & 0xff;
return $val;
} /**
* 转换一个shor字符串为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
* @author Zikie
*/ public static function shortToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
return $byt;
} /**
* 从字节数组中指定的位置读取一个Short类型的数据。
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Short类型的数据
*/ public static function bytesToShort($bytes, $position) {
$val = 0;
$val = $bytes[$position + 1] & 0xFF;
$val = $val << 8;
$val |= $bytes[$position] & 0xFF;
return $val;
} }
?>

socket.class.php  socket赋值类

<?php
define("CONNECTED", true);
define("DISCONNECTED", false); /**
* Socket class
*
*
* @author Seven
*/
Class Socket
{
private static $instance; private $connection = null; private $connectionState = DISCONNECTED; private $defaultHost = "127.0.0.1"; private $defaultPort = 80; private $defaultTimeout = 10; public $debug = false; function __construct()
{ }
/**
* Singleton pattern. Returns the same instance to all callers
*
* @return Socket
*/
public static function singleton()
{
if (self::$instance == null || ! self::$instance instanceof Socket)
{
self::$instance = new Socket(); }
return self::$instance;
}
/**
* Connects to the socket with the given address and port
*
* @return void
*/
public function connect($serverHost=false, $serverPort=false, $timeOut=false)
{
if($serverHost == false)
{
$serverHost = $this->defaultHost;
} if($serverPort == false)
{
$serverPort = $this->defaultPort;
}
$this->defaultHost = $serverHost;
$this->defaultPort = $serverPort; if($timeOut == false)
{
$timeOut = $this->defaultTimeout;
}
$this->connection = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); if(socket_connect($this->connection,$serverHost,$serverPort) == false)
{
$errorString = socket_strerror(socket_last_error($this->connection));
$this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}");
}else{
$this->_throwMsg("Socket connected!");
} $this->connectionState = CONNECTED;
} /**
* Disconnects from the server
*
* @return True on succes, false if the connection was already closed
*/
public function disconnect()
{
if($this->validateConnection())
{
socket_close($this->connection);
$this->connectionState = DISCONNECTED;
$this->_throwMsg("Socket disconnected!");
return true;
}
return false;
}
/**
* Sends a command to the server
*
* @return string Server response
*/
public function sendRequest($command)
{
if($this->validateConnection())
{
$result = socket_write($this->connection,$command,strlen($command));
return $result;
}
$this->_throwError("Sending command \"{$command}\" failed.<br>Reason: Not connected");
} public function isConn()
{
return $this->connectionState;
} public function getUnreadBytes()
{ $info = socket_get_status($this->connection);
return $info['unread_bytes']; } public function getConnName(&$addr, &$port)
{
if ($this->validateConnection())
{
socket_getsockname($this->connection,$addr,$port);
}
} /**
* Gets the server response (not multilined)
*
* @return string Server response
*/
public function getResponse()
{
$read_set = array($this->connection); while (($events = socket_select($read_set, $write_set = NULL, $exception_set = NULL, 0)) !== false)
{
if ($events > 0)
{
foreach ($read_set as $so)
{
if (!is_resource($so))
{
$this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
return false;
}elseif ( ( $ret = @socket_read($so,4096,PHP_BINARY_READ) ) == false){
$this->_throwError("Receiving response from server failed.<br>Reason: Not bytes to read");
return false;
}
return $ret;
}
}
} return false;
}
public function waitForResponse()
{
if($this->validateConnection())
{
return socket_read($this->connection, 2048);
} $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
return false;
}
/**
* Validates the connection state
*
* @return bool
*/
private function validateConnection()
{
return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED));
}
/**
* Throws an error
*
* @return void
*/
private function _throwError($errorMessage)
{
echo "Socket error: " . $errorMessage;
}
/**
* Throws an message
*
* @return void
*/
private function _throwMsg($msg)
{
if ($this->debug)
{
echo "Socket message: " . $msg . "\n\n";
}
}
/**
* If there still was a connection alive, disconnect it
*/
public function __destruct()
{
$this->disconnect();
}
} ?>

PacketBase.class.php  打包类,暂时没用到

<?php
/**
* PacketBase class
*
* 用以处理与c++服务端交互的sockets 包
*
* 注意:不支持宽字符
*
* @author Seven <seven@qoolu.com>
*
*/
class PacketBase extends ContentHandler
{
private $head;
private $params;
private $opcode;
/**************************construct***************************/
function __construct()
{
$num = func_num_args();
$args = func_get_args();
switch($num){
case 0:
//do nothing 用来生成对象的
break;
case 1:
$this->__call('__construct1', $args);
break;
case 2:
$this->__call('__construct2', $args);
break;
default:
throw new Exception();
}
}
//无参数
public function __construct1($OPCODE)
{
$this->opcode = $OPCODE;
$this->params = 0;
}
//有参数
public function __construct2($OPCODE, $PARAMS)
{
$this->opcode = $OPCODE;
$this->params = $PARAMS;
}
//析构
function __destruct()
{
unset($this->head);
unset($this->buf);
} //打包
public function pack()
{
$head = $this->MakeHead($this->opcode,$this->params);
return $head.$this->buf;
}
//解包
public function unpack($packet,$noHead = false)
{ $this->buf = $packet;
if (!$noHead){
$recvHead = unpack("S2hd/I2pa",$packet);
$SD = $recvHead[hd1];//SD
$this->contentlen = $recvHead[hd2];//content len
$this->opcode = $recvHead[pa1];//opcode
$this->params = $recvHead[pa2];//params $this->pos = 12;//去除包头长度 if ($SD != 21316)
{
return false;
}
}else
{
$this->pos = 0;
}
return true;
}
public function GetOP()
{
if ($this->buf)
{
return $this->opcode;
}
return 0;
}
/************************private***************************/
//构造包头
private function MakeHead($opcode,$param)
{
return pack("SSII","SD",$this->TellPut(),$opcode,$param);
} //用以模拟函数重载
private function __call($name, $arg)
{
return call_user_func_array(array($this, $name), $arg);
} /***********************Uitl***************************/
//将16进制的op转成10进制
static function MakeOpcode($MAJOR_OP, $MINOR_OP)
{
return ((($MAJOR_OP & 0xffff) << 16) | ($MINOR_OP & 0xffff));
}
}
/**
* 包体类
* 包含了对包体的操作
*/
class ContentHandler
{
public $buf;
public $pos;
public $contentlen;//use for unpack function __construct()
{
$this->buf = "";
$this->contentlen = 0;
$this->pos = 0;
}
function __destruct()
{
unset($this->buf);
} public function PutInt($int)
{
$this->buf .= pack("i",(int)$int);
}
public function PutUTF($str)
{
$l = strlen($str);
$this->buf .= pack("s",$l);
$this->buf .= $str;
}
public function PutStr($str)
{
return $this->PutUTF($str);
} public function TellPut()
{
return strlen($this->buf);
} /*******************************************/ public function GetInt()
{
//$cont = substr($out,$l,4);
$get = unpack("@".$this->pos."/i",$this->buf);
if (is_int($get[1])){
$this->pos += 4;
return $get[1];
}
return 0;
}
public function GetShort()
{
$get = unpack("@".$this->pos."/S",$this->buf);
if (is_int($get[1])){
$this->pos += 2;
return $get[1];
}
return 0;
}
public function GetUTF()
{
$getStrLen = $this->GetShort(); if ($getStrLen > 0)
{
$end = substr($this->buf,$this->pos,$getStrLen);
$this->pos += $getStrLen;
return $end;
}
return '';
}
/***************************/ public function GetBuf()
{
return $this->buf;
} public function SetBuf($strBuf)
{
$this->buf = $strBuf;
} public function ResetBuf(){
$this->buf = "";
$this->contentlen = 0;
$this->pos = 0;
} } ?>

PHP使用Socket发送字节流的更多相关文章

  1. C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全

    简单的c# TCP通讯(TcpListener) C# 的TCP Socket (同步方式) C# 的TCP Socket (异步方式) C# 的tcp Socket设置自定义超时时间 C# TCP ...

  2. ZeroMQ接口函数之 :zmq_msg_send – 从一个socket发送一个消息帧

    ZeroMQ 官方地址 :http://api.zeromq.org/4-0:zmq_msg_send zmq_msg_send(3) ØMQ Manual - ØMQ/3.2.5 Name zmq_ ...

  3. android firmware 利用UDP socket发送Magic Packet--python版本

    android firmware 利用UDP socket发送Magic Packet--python版本 #!/usr/bin/python import sys, time from struct ...

  4. android firmware 利用UDP socket发送Magic Packet--c语言版本

    android firmware 利用UDP socket发送Magic Packet 1 Magic Packet格式: 6个0xFF + 16个Dst Mac Address 2 代码需要设置目的 ...

  5. python socket发送魔法包网络唤醒开机.py

    python socket发送魔法包网络唤醒开机.py 现在的电脑应该都普遍支持有线网络的WOL了,支持无线网络唤醒的电脑,可能比较少. """ python socke ...

  6. php 利用socket发送GET,POST请求

    作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步.最近我一直在学习php的关于http的编程,许多东西恍然大悟,受益匪浅.希望分享给大家.本文需要有一定http ...

  7. socket发送和接收数据

    1)sendBuf(),sendText(),sendStream() 几乎所有的通信控件都会提供上面的3个方法.首先看看SendBuf(). function TCustomWinSocket.Se ...

  8. c++如何使用SOCKET 发送HTTP1.1 GET POST请求包

    如何使用SOCKET 发送HTTP1.1 GET POST请求包 分类: 无线通信 C/C++2009-10-29 10:58 14259人阅读 评论(15) 收藏 举报 socket服务器actio ...

  9. 利用 socket 发送 get/post 请求

    思路:利用 fsockopen 函数与要请求的主机建立一个通信通道,再将请求行.头信息.主体信息通过这个通道传输给主机实现请求的发送.利用这种方式发送 get 请求就是常说的小偷程序,发送 post ...

随机推荐

  1. 记录用到的一些linux命令和疑难解决

    1. 用gedit打开.bashrc larry@larry-Rev:~$ sudo gedit ~/.bashrc 2. ubuntu里安装软件有点像iOS里的Cydia,要添加软件源来在Ubunt ...

  2. 「CQOI2007」「BZOJ1260」涂色paint (区间dp

    1260: [CQOI2007]涂色paint Time Limit: 30 Sec  Memory Limit: 64 MBSubmit: 2057  Solved: 1267[Submit][St ...

  3. spring boot 部署 发布

    Spring Boot应用的打包和部署 字数639 阅读2308 评论0 喜欢5 现在的IT开发,DevOps渐渐获得技术管理人员支持.云计算从ECS转向Docker容器技术.微服务的概念和讨论也越来 ...

  4. 各浏览器userAgent汇总

    浏览器  navigator.userAgent  备注  IE6  Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)   IE7  Mo ...

  5. json对象和json数组

    json字符串对象和json字符串数组:JSONArray跟JSONObject的区别就是JSONArray比JSONObject多中括号[] jsonObject: "Row": ...

  6. python 之 exec命令

    参数1:字符串形式的命令 参数2:全局作用域(字典形式),如果不指定默认使用globals() 参数3:局部作用域(字典形式),如果不指定默认使用locals() g= { 'x':1, 'y':2 ...

  7. c++函数模板1

    1 定义: 函数模板 只适用于参数个数相同但是类型不同 而且函数体相同的情况 2 这个例子没有使用模板的情况 #include <iostream> using namespace std ...

  8. dataTables使用ajax请求显示数据

    dataTables是一种很好用前端表格显示库.当加载大量数据时,可以用Ajax 获取数据来提高效率,增速网页加载速率.下面以一个例子作示范. 首先,需要下载jQuery以及dataTables库.这 ...

  9. PHP实现人脸识别技术

    这次人脸识别技术,是实现在微信端的,也就是说利用公众微信平台,调用第三的API来实现人脸识别这项技术的. 实现的思路: 首先呢,将收集的照片,建立一个照片库,然后利用在微信平台发送的照片,去到照片库进 ...

  10. swift日期操作

    简介:本文将介绍一些关于swift中对于日期的格式化与获取,支持swift4.0 extension Date { //格式化日期 func getDateString() -> String{ ...