Socket.class.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. class Socket {
  12. protected $_config = array(
  13. 'persistent' => false,
  14. 'host' => 'localhost',
  15. 'protocol' => 'tcp',
  16. 'port' => 80,
  17. 'timeout' => 30
  18. );
  19. public $config = array();
  20. public $connection = null;
  21. public $connected = false;
  22. public $error = array();
  23. public function __construct($config = array()) {
  24. $this->config = array_merge($this->_config,$config);
  25. if (!is_numeric($this->config['protocol'])) {
  26. $this->config['protocol'] = getprotobyname($this->config['protocol']);
  27. }
  28. }
  29. public function connect() {
  30. if ($this->connection != null) {
  31. $this->disconnect();
  32. }
  33. if ($this->config['persistent'] == true) {
  34. $tmp = null;
  35. $this->connection = @pfsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
  36. } else {
  37. $this->connection = fsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
  38. }
  39. if (!empty($errNum) || !empty($errStr)) {
  40. $this->error($errStr, $errNum);
  41. }
  42. $this->connected = is_resource($this->connection);
  43. return $this->connected;
  44. }
  45. public function error() {
  46. }
  47. public function write($data) {
  48. if (!$this->connected) {
  49. if (!$this->connect()) {
  50. return false;
  51. }
  52. }
  53. return fwrite($this->connection, $data, strlen($data));
  54. }
  55. public function read($length=1024) {
  56. if (!$this->connected) {
  57. if (!$this->connect()) {
  58. return false;
  59. }
  60. }
  61. if (!feof($this->connection)) {
  62. return fread($this->connection, $length);
  63. } else {
  64. return false;
  65. }
  66. }
  67. public function disconnect() {
  68. if (!is_resource($this->connection)) {
  69. $this->connected = false;
  70. return true;
  71. }
  72. $this->connected = !fclose($this->connection);
  73. if (!$this->connected) {
  74. $this->connection = null;
  75. }
  76. return !$this->connected;
  77. }
  78. public function __destruct() {
  79. $this->disconnect();
  80. }
  81. }