<?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获取数据类的更多相关文章

  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. hive日期函数

    今天select from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss') UNIX时间戳转日期函数: from_unixtime 语法: from_ ...

  2. 高亮代码显示之HTML困惑

    近期做样式库,需要将HTML代码高亮,开始寻找相关的插件. 看到highlight.js,看到它主题样式如此之多,支持语言也如此之多,以为找到了神器.不想这只是痛苦的开始,为了让它支持HTML,我尝试 ...

  3. log4j按级别输出日志文件

    log4j.properties: BASE_DIR= /home/admin/preprocess-tmc-city/logs log4j.rootLogger=debug,stdout,debug ...

  4. c++的类与对象

    对象:此对象,非彼对象,:-D,跟妹子无关(不过貌似也可以,,),闲言少叙,书归正传 我们可以把我们见到的一切事物都称为对象.它可以有形,可以无形,可以简单,可以复杂,但是对某一种具体的对象,比如公司 ...

  5. JavaScript(复习总结)

    一.三个常用对话框 1.alert(""):警告对话框,作用是弹出一个警告对话框(最常用) 2.confirm(""):确定对话框,弹出一个带确定和取消按钮的对 ...

  6. 记一次未解决的异常:java.lang.NoClassDefFoundError: net/sf/json/JSONObject

    原因:Jetty会导致这个问题,Tomcat可以正常启动   一.异常产生现象 使用json-lib转换实体类/字符串,跑单元测试没问题,但是启动jetty后调用JSONArray.fromObjec ...

  7. PHP调试总结

    PHP调试总结一,环境方面,比如查看安装扩展是否生效,是总支持某扩展.可以在web目录中建一个phpinfo.php在里面输入<?phpphpinfo();?>在浏览器上访问一下,会输出P ...

  8. jqeury datatable

    1.自定义列信息    "aoColumnDefs":[                               {                               ...

  9. 基于WebView的混合编程

    近日公司需求变更,以前一个页面是后台返回HTML字段,然后我们直接用webView接收,现在新增一个页面,数据后台返回非HTML,页面跟前面一直,所幸自己会点HTML,所以偷了个懒,自己用代码把数据组 ...

  10. nwe

    SELECT  SUBSTR('20150601', 1, 6) AS CALC_MONTH,       CHN.EMPLOYEE_CODE,       CHN.CHANNEL_TYPE,     ...