很簡單的一個socket用戶端PHP類

來源:互聯網
上載者:User
php 5,需要開啟socket擴充
  1. //socke操作類
  2. class Socket {
  3. private $host;//串連socket的主機
  4. private $port;//socket的連接埠號碼
  5. private $error=array();
  6. private $socket=null;//socket的串連標識
  7. private $queryStr="";//發送的資料
  8. public function __construct($host,$port) {
  9. if(!extension_loaded("sockets")){
  10. exit("請開啟socket擴充 ");
  11. }
  12. if(empty($host)) exit("請輸入目標地址");
  13. if(empty($port)) exit("請輸入有效連接埠號碼");
  14. $this->host=$host;
  15. $this->port=$port;
  16. $this->CreateSocket();//建立串連
  17. }
  18. //建立socket
  19. private function CreateSocket(){
  20. !$this->socket&&$this->socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//建立socket
  21. $r=@socket_connect($this->socket,$this->host,$this->port);
  22. if($r){
  23. return $r;
  24. }else{
  25. $this->error[]=socket_last_error($this->socket);
  26. return false;
  27. }
  28. }
  29. //向socket伺服器寫入資料並讀取
  30. public function wr($contents){
  31. $this->queryStr="";
  32. $this->queryStr=$contents;
  33. !$this->socket&&$this->CreateSocket();
  34. $contents=$this->fliterSendData($contents);
  35. $result=socket_write($this->socket,$contents,strlen($contents));
  36. if(!intval($result)){
  37. $this->error[]=socket_last_error($this->socket);
  38. return false;
  39. }
  40. $response=socket_read($this->socket,12048);
  41. if(false===$response){
  42. $this->error[]=socket_last_error($this->socket);
  43. return false;
  44. }
  45. return $response;
  46. }
  47. //對發送的資料進行過濾
  48. private function fliterSendData($contents){
  49. //對寫入的資料進行處理
  50. return $contents;
  51. }
  52. //所有錯誤資訊
  53. public function getError(){
  54. return $this->error;
  55. }
  56. //最後一次錯誤資訊
  57. public function getLastError(){
  58. return $this->error(count($this->error));
  59. }
  60. //擷取最後一次發送的訊息
  61. public function getLastMsg(){
  62. return $this->queryStr;
  63. }
  64. public function getHost(){
  65. return $this->host;
  66. }
  67. public function getPort(){
  68. return $this->port;
  69. }
  70. //關閉socket串連
  71. private function close(){
  72. $this->socket&&socket_close($this->socket);//關閉串連
  73. $this->socket=null;//串連資源初始化
  74. }
  75. public function __destruct(){
  76. $this->close();
  77. }
  78. }
複製代碼
很簡單, socket, PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.