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 ...
随机推荐
- dedecms代码研究六
今天讲的是dedecms最关键的东西,模板分析啦.也就是dedetag.class.php 里面的ParseTemplet方法 模板解析方法 先看看一个dedecms标签,大家心里有个数: {dede ...
- 也说virtualbox下安装centos7
以前一直在VMware Workstation下安装虚拟机系统,这几天由于电脑被别人使用误升级为win10,而导致原来的LNMP不能使用,查找原因在于即使是最新的VM12.1.1也只是支持win8而已 ...
- Java中的字符串常量池
ava中字符串对象创建有两种形式,一种为字面量形式,如String str = "droid";,另一种就是使用new这种标准的构造对象的方法,如String str = new ...
- notepad++ 正则表达式
body { font-family: Bitstream Vera Sans Mono; font-size: 11pt; line-height: 1.5; } html, body { colo ...
- javaweb学习第一天 debug
debug 断点: f5:step into f6:step over f7:step return drop to frame:跳到当前方法的的第一行 resume:跳到下一个断点 watch:观察 ...
- 关于 this 和 prototype 的理解
1:this 的理解比较好的书是 <Javascript语言精粹> 平时我们全局写 var a = 1, 其实就是 window.a = 1; var f = function(){}, ...
- Unity协程(Coroutine)原理深入剖析
Unity协程(Coroutine)原理深入剖析 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com 其实协程并没有那么复杂,网上很多地方都说是多 ...
- android 学习(1)
第二次发生这种事了,写完啦,手一抖,丢了,这个写完不用博客园了,怪不得用户越来越少 简写 androidstudio安装注意点 1JDK安装需配置环境变量 2安装遇到haxm错误需要进入BIOS打开C ...
- WebService 基础使用&cxf第三方Service使用
1.通过Jax-ws自己发布一个webservice 解析:用webservice发布HelloWorld JAX-WS本质就是通过Socket来实现的.2.WSDL文档描述如何直接变成java代码 ...
- B. Santa Claus and Keyboard Check 模拟
http://codeforces.com/contest/752/problem/B uuu yyu xy xx 注意变化了之后,检查一次前面已经变化过的就好.因为可能前面的满足,但是变了后不满足. ...