php Socket 创建 监听等实例
本文章提供在php中socket相关函数的实例,如果创建Socket 接受一个socket连接 写入一个Socket 初始化连接等操作,实例代码如下:
- $ip="127.0.0.1";
- $port=1000;
- $socket=socket_create(af_inet,sock_stream,sol_tcp);
- $bind=socket_bind($socket,$ip,$prot);
- $listen=socket_listen($socket);
- $msg=socket_accept($socket);
- $welcome="欢迎来到php服务/n";
- socket_write($msg,$welcome,strlen($welcome));
- socket_close($socket);
-
- */
-
- $ip="127.0.0.1";
- $port=1000;
- $socket=socket_create(af_inet,sock_stream,sol_tcp);
- socket_clear_error($socket);
- socket_close($socket);
-
-
-
-
-
- $sockets=array();
-
- if(!socket_create_pair(af_unix,sock_stream,0,$sockets))
- {
- echo socket_strerror(socket_last_error());
- }
-
- if(!socket_write($sockets[0],"abcdef123n",strlen("abcdef123n"))) //开源代码phpfensi.com
- {
- cho socket_strerror(socket_last_error());
- }
- if(!$data=socket_read($sockets[1],strlen("abcdef123n"),php_binary_read))
- {
- echo socket_strerror(socket_last_error());
- }
- var_dump($data);
-
- socket_close($sockets[0]);
- socket_close($sockets[1]);
-
-
-
-
- $ip="127.0.0.1";
- $port=1000;
- $socket=socket_create(af_inet,sock_stream,sol_tcp);
- socket_set_nonblock($socket);
- socket_connect($socket,$ip,$port);
- socket_set_block($sock);
- switch(socket_select($r=array($socket),$w=array($socket),$f=array($socket),5))
- {
- case 2:
- echo "连接被拒绝!n";
- break;
- case 1:
- echo "成功连接n";
- break;
- case 0:
- echo "连接超时n";
- break;
- }
-
-
-
-
-
-
- class socketlistener extends socket
- {
- function __construct($port=null)
- {
- $this->stream=@socket_create_listen($port?$port:port);
- }
- function isactive()
- {
- if($this->stream)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }