Heim  >  Artikel  >  Backend-Entwicklung  >  很简单的一个socket客户端PHP类

很简单的一个socket客户端PHP类

WBOY
WBOYOriginal
2016-07-25 08:42:28896Durchsuche
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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:验证身份证是否合法的PHP函数 Nächster Artikel:PHP邮件操作类