1. <?php
  2. define("CONNECTED", true);
  3. define("DISCONNECTED", false);
  4.  
  5. /**
  6. * Socket class
  7. *
  8. *
  9. * @author ZT
  10. */
  11. Class Socket
  12. {
  13. private static $instance;
  14.  
  15. private $connection = null;
  16.  
  17. private $connectionState = DISCONNECTED;
  18.  
  19. private $defaultHost = "127.0.0.1";
  20.  
  21. private $defaultPort = 80;
  22.  
  23. private $defaultTimeout = 20;
  24.  
  25. public $debug = false;
  26.  
  27. function __construct()
  28. {
  29.  
  30. }
  31. /**
  32. * Singleton pattern. Returns the same instance to all callers
  33. *
  34. * @return Socket
  35. */
  36. public static function singleton()
  37. {
  38. if (self::$instance == null || ! self::$instance instanceof Socket)
  39. {
  40. self::$instance = new Socket();
  41.  
  42. }
  43. return self::$instance;
  44. }
  45. /**
  46. * Connects to the socket with the given address and port
  47. *
  48. * @return void
  49. */
  50. public function connect($serverHost=false, $serverPort=false, $timeOut=false)
  51. {
  52. if($serverHost == false)
  53. {
  54. $serverHost = $this->defaultHost;
  55. }
  56.  
  57. if($serverPort == false)
  58. {
  59. $serverPort = $this->defaultPort;
  60. }
  61. $this->defaultHost = $serverHost;
  62. $this->defaultPort = $serverPort;
  63.  
  64. if($timeOut == false)
  65. {
  66. $timeOut = $this->defaultTimeout;
  67. }
  68. $this->connection = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
  69.  
  70. if(socket_connect($this->connection,$serverHost,$serverPort) == false)
  71. {
  72. $errorString = socket_strerror(socket_last_error($this->connection));
  73. $this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}");
  74. }else{
  75. $this->_throwMsg("Socket connected!");
  76. }
  77.  
  78. $this->connectionState = CONNECTED;
  79. }
  80.  
  81. /**
  82. * Disconnects from the server
  83. *
  84. * @return True on succes, false if the connection was already closed
  85. */
  86. public function disconnect()
  87. {
  88. if($this->validateConnection())
  89. {
  90. socket_close($this->connection);
  91. $this->connectionState = DISCONNECTED;
  92. $this->_throwMsg("Socket disconnected!");
  93. return true;
  94. }
  95. return false;
  96. }
  97. /**
  98. * Sends a command to the server
  99. *
  100. * @return string Server response
  101. */
  102. public function sendRequest($command)
  103. {
  104. if($this->validateConnection())
  105. {
  106. $result = socket_write($this->connection,$command,strlen($command));
  107. return $result;
  108. }
  109. $this->_throwError("Sending command \"{$command}\" failed.<br>Reason: Not connected");
  110. }
  111.  
  112. public function isConn()
  113. {
  114. return $this->connectionState;
  115. }
  116.  
  117. public function getUnreadBytes()
  118. {
  119.  
  120. $info = socket_get_status($this->connection);
  121. return $info['unread_bytes'];
  122.  
  123. }
  124.  
  125. public function getConnName(&$addr, &$port)
  126. {
  127. if ($this->validateConnection())
  128. {
  129. socket_getsockname($this->connection,$addr,$port);
  130. }
  131. }
  132.  
  133. /**
  134. * Gets the server response (not multilined)
  135. *
  136. * @return string Server response
  137. */
  138. public function getResponse()
  139. {
  140. $read_set = array($this->connection);
  141.  
  142. while (($events = socket_select($read_set, $write_set = NULL, $exception_set = NULL, 0)) !== false)
  143. {
  144. if ($events > 0)
  145. {
  146. foreach ($read_set as $so)
  147. {
  148. if (!is_resource($so))
  149. {
  150. $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
  151. return false;
  152. }elseif ( ( $ret = @socket_read($so,4096,PHP_BINARY_READ) ) == false){
  153. $this->_throwError("Receiving response from server failed.<br>Reason: Not bytes to read");
  154. return false;
  155. }
  156. return $ret;
  157. }
  158. }
  159. }
  160.  
  161. return false;
  162. }
  163. public function waitForResponse()
  164. {
  165. if($this->validateConnection())
  166. {
  167. $socketResponse = "";
  168. while($val = socket_read($this->connection, 1024)){
  169. $socketResponse .= $val;
  170. }
  171. return $socketResponse;
  172. }
  173.  
  174. $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
  175. return false;
  176. }
  177. /**
  178. * Validates the connection state
  179. *
  180. * @return bool
  181. */
  182. private function validateConnection()
  183. {
  184. return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED));
  185. }
  186. /**
  187. * Throws an error
  188. *
  189. * @return void
  190. */
  191. private function _throwError($errorMessage)
  192. {
  193. echo "Socket error: " . $errorMessage;
  194. }
  195. /**
  196. * Throws an message
  197. *
  198. * @return void
  199. */
  200. private function _throwMsg($msg)
  201. {
  202. if ($this->debug)
  203. {
  204. echo "Socket message: " . $msg . "\n\n";
  205. }
  206. }
  207. /**
  208. * If there still was a connection alive, disconnect it
  209. */
  210. public function __destruct()
  211. {
  212. $this->disconnect();
  213. }
  214. }

读取数据使用waitForResponse()方法

示例代码:

  1. function send_socket($req, $ip, $port){
  2. $byte = new Bytes();
  3. $req_bytes = $byte->getbytes($req);
  4. $req_trans = $byte->tostr($req_bytes);
  5. $req_length = strlen($req_trans);
  6. $pack = pack("a{$req_length}", $req_trans);
  7.  
  8. $socket = Socket::singleton();
  9. $socket->connect($ip, $port);
  10. $socket->sendRequest($pack);
  11.  
  12. $socket_result = $socket->waitForResponse();
  13.  
  14. $socket->disconnect();
  15. return $socket_result;
  16. }
  17.  
  18. var_dump(send_socket("test", "127.0.0.1", 443));

php socket获取数据类的更多相关文章

  1. 2、 Spark Streaming方式从socket中获取数据进行简单单词统计

    Spark 1.5.2 Spark Streaming 学习笔记和编程练习 Overview 概述 Spark Streaming is an extension of the core Spark ...

  2. 【Spark】通过SparkStreaming实现从socket接受数据,并进行简单的单词计数

    文章目录 步骤 一.创建maven工程并导入jar包 二.安装并启动生产者 三.开发SparkStreaming代码 四.查看结果 步骤 一.创建maven工程并导入jar包 <properti ...

  3. WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据

    WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...

  4. WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据(转)

    WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...

  5. Python Socket请求网站获取数据

     Python Socket请求网站获取数据 ---阻塞 I/O     ->收快递,快递如果不到,就干不了其他的活 ---非阻塞I/0 ->收快递,不断的去问,有没有送到,有没有送到,. ...

  6. php根据地理坐标获取国家、省份、城市,及周边数据类

    功能:当App获取到用户的地理坐标时,可以根据坐标知道用户当前在那个国家.省份.城市,及周边有什么数据. 原理:基于百度Geocoding API 实现,需要先注册百度开发者,然后申请百度AK(密钥) ...

  7. php依据地理坐标获取国家、省份、城市,及周边数据类

    功能:当App获取到用户的地理坐标时,能够依据坐标知道用户当前在那个国家.省份.城市.及周边有什么数据. 原理:基于百度Geocoding API 实现.须要先注冊百度开发人员.然后申请百度AK(密钥 ...

  8. 【记录】mybatis中获取常量类中数据

    部分转载,已注明来源: 1.mybatis中获取常量类中数据 <update id="refuseDebt"> UPDATE dt_debt a SET         ...

  9. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

随机推荐

  1. host DNS 访问规则

    昨天站点一直出现302循环重定向问题,捣鼓了半天才解决,原来是hosts和dns配置问题. 注:当你的站点出现循环重定向时,首先应该关注的hosts以及dns配置,确保无误. 下面记录下相关知识点: ...

  2. 【T电商】 maven初识

    PS:本篇博客,就是对于maven的一个简单的总结,认识.可能更多的是借鉴别人的看法,然后结合自己的使用,再加以说明. 首先,什么是maven: Apache Maven is a software ...

  3. [转载]:经纬度与WGS84坐标转换

    本代码实现在WGS84系统的大地坐标(BLH)和空间直角坐标(XYZ)的互相转换,符合标准语法,可直接使用 如下代码,输出为: WGS84:  -2175790.73969891    4461032 ...

  4. MXS 编辑器外观

    Tool > Open User Options File # Give symbolic names to the set of colours used in the standard st ...

  5. C++学习基础七——深复制与浅复制

    一.深复制与浅复制基本知识 深复制和浅复制,又称为深拷贝和浅拷贝. 深复制和浅复制的区别如下图1所示: 图1 图1表示的是,定义一个类CDemo,包含int a和char *str两个成员变量, 当深 ...

  6. js分辨浏览器类别和版本

    function BrowserInfo() { var ua = navigator.userAgent.toLowerCase(); var Sys = {}; var s; (s = ua.ma ...

  7. COM符合名字对象建议使用的分隔符

  8. Add Binary <leetcode>

    Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...

  9. eval()与jQuery.parseJSON()的差别以及常见的解析缺少分号的问题

    在数据传输过程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象 http://blog.163.com/wujicaiguai%40126/blog/static/1701715 ...

  10. asdsa

    ML_运营一部数据平台应用服务组 <ML_1731@pingan.com.cn> epcischagentdailyreportkb copy from OLAPSEL/frt9iora@ ...