php socket获取数据类
- <?php
- define("CONNECTED", true);
- define("DISCONNECTED", false);
- /**
- * Socket class
- *
- *
- * @author ZT
- */
- Class Socket
- {
- private static $instance;
- private $connection = null;
- private $connectionState = DISCONNECTED;
- private $defaultHost = "127.0.0.1";
- private $defaultPort = 80;
- private $defaultTimeout = 20;
- 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())
- {
- $socketResponse = "";
- while($val = socket_read($this->connection, 1024)){
- $socketResponse .= $val;
- }
- return $socketResponse;
- }
- $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();
- }
- }
读取数据使用waitForResponse()方法
示例代码:
- function send_socket($req, $ip, $port){
- $byte = new Bytes();
- $req_bytes = $byte->getbytes($req);
- $req_trans = $byte->tostr($req_bytes);
- $req_length = strlen($req_trans);
- $pack = pack("a{$req_length}", $req_trans);
- $socket = Socket::singleton();
- $socket->connect($ip, $port);
- $socket->sendRequest($pack);
- $socket_result = $socket->waitForResponse();
- $socket->disconnect();
- return $socket_result;
- }
- var_dump(send_socket("test", "127.0.0.1", 443));
php socket获取数据类的更多相关文章
- 2、 Spark Streaming方式从socket中获取数据进行简单单词统计
Spark 1.5.2 Spark Streaming 学习笔记和编程练习 Overview 概述 Spark Streaming is an extension of the core Spark ...
- 【Spark】通过SparkStreaming实现从socket接受数据,并进行简单的单词计数
文章目录 步骤 一.创建maven工程并导入jar包 二.安装并启动生产者 三.开发SparkStreaming代码 四.查看结果 步骤 一.创建maven工程并导入jar包 <properti ...
- WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据
WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...
- WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据(转)
WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据 WebForm1.aspx 页面 (原生AJAX请求,写法一) <%@ Page Langu ...
- Python Socket请求网站获取数据
Python Socket请求网站获取数据 ---阻塞 I/O ->收快递,快递如果不到,就干不了其他的活 ---非阻塞I/0 ->收快递,不断的去问,有没有送到,有没有送到,. ...
- php根据地理坐标获取国家、省份、城市,及周边数据类
功能:当App获取到用户的地理坐标时,可以根据坐标知道用户当前在那个国家.省份.城市,及周边有什么数据. 原理:基于百度Geocoding API 实现,需要先注册百度开发者,然后申请百度AK(密钥) ...
- php依据地理坐标获取国家、省份、城市,及周边数据类
功能:当App获取到用户的地理坐标时,能够依据坐标知道用户当前在那个国家.省份.城市.及周边有什么数据. 原理:基于百度Geocoding API 实现.须要先注冊百度开发人员.然后申请百度AK(密钥 ...
- 【记录】mybatis中获取常量类中数据
部分转载,已注明来源: 1.mybatis中获取常量类中数据 <update id="refuseDebt"> UPDATE dt_debt a SET ...
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
随机推荐
- host DNS 访问规则
昨天站点一直出现302循环重定向问题,捣鼓了半天才解决,原来是hosts和dns配置问题. 注:当你的站点出现循环重定向时,首先应该关注的hosts以及dns配置,确保无误. 下面记录下相关知识点: ...
- 【T电商】 maven初识
PS:本篇博客,就是对于maven的一个简单的总结,认识.可能更多的是借鉴别人的看法,然后结合自己的使用,再加以说明. 首先,什么是maven: Apache Maven is a software ...
- [转载]:经纬度与WGS84坐标转换
本代码实现在WGS84系统的大地坐标(BLH)和空间直角坐标(XYZ)的互相转换,符合标准语法,可直接使用 如下代码,输出为: WGS84: -2175790.73969891 4461032 ...
- MXS 编辑器外观
Tool > Open User Options File # Give symbolic names to the set of colours used in the standard st ...
- C++学习基础七——深复制与浅复制
一.深复制与浅复制基本知识 深复制和浅复制,又称为深拷贝和浅拷贝. 深复制和浅复制的区别如下图1所示: 图1 图1表示的是,定义一个类CDemo,包含int a和char *str两个成员变量, 当深 ...
- js分辨浏览器类别和版本
function BrowserInfo() { var ua = navigator.userAgent.toLowerCase(); var Sys = {}; var s; (s = ua.ma ...
- COM符合名字对象建议使用的分隔符
- Add Binary <leetcode>
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- eval()与jQuery.parseJSON()的差别以及常见的解析缺少分号的问题
在数据传输过程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象 http://blog.163.com/wujicaiguai%40126/blog/static/1701715 ...
- asdsa
ML_运营一部数据平台应用服务组 <ML_1731@pingan.com.cn> epcischagentdailyreportkb copy from OLAPSEL/frt9iora@ ...