> php教程 > php手册 > 본문

php socket通信演示以及socket操作类,phpsocket

WBOY
풀어 주다: 2016-06-13 08:40:46
원래의
1207명이 탐색했습니다.

php socket通信演示以及socket操作类,phpsocket

  

  准备做Java的课程设计,一个通讯录。采用C/S架构。客户端用java FX和Java,服务器端用php,采用socket通信。

  下面来讲一讲php的socket通信:

  之前,得先讲一下TCP/IP,UDP。随着互联网应用的日益广泛,相信很多人或多或少都听说过这些协议,那么到底它们是什么呢?

  1、什么是TCP/IP、UDP?

         TCP/IP(Transmission Control Protocol/Internet Protocol)即传输控制协议/网间协议,是一个工业标准的协议集,它是为广域网(WANs)设计的。TCP/IP协议族包括运输层、网络层、链路层。
         UDP(User Data Protocol,用户数据报协议)是与TCP相对应的协议。它是属于TCP/IP协议族中的一种。

            下面我们上图直观地展示一下它们的关系:

               

   这里并没有socket什么事,那socket到底在哪里呢?又有什么用?别急,接下来我们就来介绍一下socket与它们的关系。同样上图。

      
    现在明白它们的关系了吧。那socket到底是什么?又有什么用?

       2、socket是什么?有什么用?

    Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。

       既然socket是一组封装好的接口,那我们如何去运用它来通信呢?具体是一个什么流程呢?我们可以详细一下我们打电话的过程。首先我们的电话肯定是处于监听状态的,没错吧。如果不是,那肯定也不会接到别人打的电话。当被人打电话过来时,首先是先拨号,号码是目标,也是唯一的。拨号后电话会开始连接,接通了之后就可以开始交谈,聊完了之后要挂断电话,这样别人才能再打通这个号码。 socket也是一样的,服务器端要先建立socket监听自己电脑某个端口,当有客户端创建socket发起连接请求时接受,这样就可以开始传递信息了,传输完之后再把socket关闭。当然,服务器端也可以主动向客户端发起连接请求然后开始通信。这是区别于ajax,是可以双向通信的。下面看图:

        

  先从服务器端说起。服务器端先初始化Socket,然后与端口绑定(bind),对端口进行监听(listen),调用accept阻塞,等待客户端连接。在这时如果有个客户端初始化一个Socket,然后连接服务器(connect),如果连接成功,这时客户端与服务器端的连接就建立了。客户端发送数据请求,服务器端接收请求并处理请求,然后把回应数据发送给客户端,客户端读取数据,最后关闭连接,一次交互结束

 

       3、socket的相关函数 :

socket_accept() 接受一个Socket连接
socket_bind() 把socket绑定在一个IP地址和端口上
socket_clear_error() 清除socket的错误或最后的错误代码
socket_close() 关闭一个socket资源
socket_connect() 开始一个socket连接
socket_create_listen() 在指定端口打开一个socket监听
socket_create_pair() 产生一对没有差别的socket到一个数组里
socket_create() 产生一个socket,相当于产生一个socket的数据结构
socket_get_option() 获取socket选项
socket_getpeername() 获取远程类似主机的ip地址
socket_getsockname() 获取本地socket的ip地址
socket_iovec_add() 添加一个新的向量到一个分散/聚合的数组
socket_iovec_alloc() 这个函数创建一个能够发送接收读写的iovec数据结构
socket_iovec_delete() 删除一个已分配的iovec
socket_iovec_fetch() 返回指定的iovec资源的数据
socket_iovec_free() 释放一个iovec资源
socket_iovec_set() 设置iovec的数据新值
socket_last_error() 获取当前socket的最后错误代码
socket_listen() 监听由指定socket的所有连接
socket_read() 读取指定长度的数据
socket_readv() 读取从分散/聚合数组过来的数据
socket_recv() 从socket里结束数据到缓存
socket_recvfrom() 接受数据从指定的socket,如果没有指定则默认当前socket
socket_recvmsg() 从iovec里接受消息
socket_select() 多路选择
socket_send() 这个函数发送数据到已连接的socket
socket_sendmsg() 发送消息到socket
socket_sendto() 发送消息到指定地址的socket
socket_set_block() 在socket里设置为块模式
socket_set_nonblock() socket里设置为非块模式
socket_set_option() 设置socket选项
socket_shutdown() 这个函数允许你关闭读、写、或指定的socket
socket_strerror() 返回指定错误号的周详错误
socket_write() 写数据到socket缓存
socket_writev() 写数据到分散/聚合数组

 

 

4、socket通信演示:

//服务器端:<br /><?<span>php
</span><span>//</span><span>确保在连接客户端时不会超时</span>
<span>set_time_limit</span>(0<span>);

</span><span>$ip</span> = '127.0.0.1'<span>;
</span><span>$port</span> = 1935<span>;

</span><span>/*</span><span>
 +-------------------------------
 *    @socket通信整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_bind
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 </span><span>*/</span>

<span>if</span>((<span>$sock</span> = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0<span>) {
    </span><span>echo</span> "socket_create() 失败的原因是:".socket_strerror(<span>$sock</span>)."\n"<span>;
}

</span><span>if</span>((<span>$ret</span> = socket_bind(<span>$sock</span>,<span>$ip</span>,<span>$port</span>)) < 0<span>) {
    </span><span>echo</span> "socket_bind() 失败的原因是:".socket_strerror(<span>$ret</span>)."\n"<span>;
}

</span><span>if</span>((<span>$ret</span> = socket_listen(<span>$sock</span>,4)) < 0<span>) {
    </span><span>echo</span> "socket_listen() 失败的原因是:".socket_strerror(<span>$ret</span>)."\n"<span>;
}

</span><span>$count</span> = 0<span>;

</span><span>do</span><span> {
    </span><span>if</span> ((<span>$msgsock</span> = socket_accept(<span>$sock</span>)) < 0<span>) {
        </span><span>echo</span> "socket_accept() failed: reason: " . socket_strerror(<span>$msgsock</span>) . "\n"<span>;
        </span><span>break</span><span>;
    } </span><span>else</span><span> {
        
        </span><span>//</span><span>发到客户端</span>
        <span>$msg</span> ="测试成功!\n"<span>;
        socket_write(</span><span>$msgsock</span>, <span>$msg</span>, <span>strlen</span>(<span>$msg</span><span>));
        
        </span><span>echo</span> "测试成功了啊\n"<span>;
        </span><span>$buf</span> = socket_read(<span>$msgsock</span>,8192<span>);
        
        
        </span><span>$talkback</span> = "收到的信息:<span>$buf</span>\n"<span>;
        </span><span>echo</span> <span>$talkback</span><span>;
        
        </span><span>if</span>(++<span>$count</span> >= 5<span>){
            </span><span>break</span><span>;
        };
        
    
    }
    socket_close(</span><span>$msgsock</span><span>);

} </span><span>while</span> (<span>true</span><span>);

socket_close(</span><span>$sock</span><span>);
</span>?>
로그인 후 복사
//客户端<br /><?<span>php
</span><span>error_reporting</span>(<span>E_ALL</span><span>);
</span><span>set_time_limit</span>(0<span>);

</span><span>$ip</span> = "127.0.0.1"<span>;
</span><span>$port</span> = 1935<span>;
</span><span>/*</span><span>
 +-------------------------------
 *    @socket连接整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 </span><span>*/</span>

<span>$socket</span> = socket_create(AF_INET, SOCK_STREAM,<span> SOL_TCP);
</span><span>if</span> (<span>$socket</span> < 0<span>) {
    </span><span>echo</span> "socket_create() failed: reason: " . socket_strerror(<span>$socket</span>) . "\n"<span>;
}</span><span>else</span><span> {
    </span><span>echo</span> "OK.\n"<span>;
}

</span><span>echo</span> "试图连接 '<span>$ip</span>' 端口 '<span>$port</span>'...\n"<span>;
</span><span>$result</span> = socket_connect(<span>$socket</span>, <span>$ip</span>, <span>$port</span><span>);
</span><span>if</span> (<span>$result</span> < 0<span>) {
    </span><span>echo</span> "socket_connect() failed.\nReason: (<span>$result</span>) " . socket_strerror(<span>$result</span>) . "\n"<span>;
}</span><span>else</span><span> {
    </span><span>echo</span> "连接OK\n"<span>;
}

</span><span>$in</span> = "Ho\r\n"<span>;
</span><span>$in</span> .= "first blood\r\n"<span>;
</span><span>$out</span> = ''<span>;

</span><span>if</span>(!socket_write(<span>$socket</span>, <span>$in</span>, <span>strlen</span>(<span>$in</span><span>))) {
    </span><span>echo</span> "socket_write() failed: reason: " . socket_strerror(<span>$socket</span>) . "\n"<span>;
}</span><span>else</span><span> {
    </span><span>echo</span> "发送到服务器信息成功!\n"<span>;
    </span><span>echo</span> "发送的内容为:<font color='red'><span>$in</span></font> <br>"<span>;
}

</span><span>while</span>(<span>$out</span> = socket_read(<span>$socket</span>, 8192<span>)) {
    </span><span>echo</span> "接收服务器回传信息成功!\n"<span>;
    </span><span>echo</span> "接受的内容为:",<span>$out</span><span>;
}


</span><span>echo</span> "关闭SOCKET...\n"<span>;
socket_close(</span><span>$socket</span><span>);
</span><span>echo</span> "关闭OK\n"<span>;
</span>?>
로그인 후 복사

  注意:1)服务器端要用CLI方式运行,也就是命令行模式运行。不要用CGI方式(浏览器访问);找到php.exe所在目录,然后运行以下代码,php 服务器文件;

    

2)运行之后可以另开dos窗口下运行netstat -ano查看端口占用情况。

    

  5、把socket封装成类:

<span>//ServerSocket.class.php<br />//客户端socket操作类</span>
로그인 후 복사
<?<span>php
   </span><span>error_reporting</span>(<span>E_ALL</span><span>);
   </span><span>set_time_limit</span>(0<span>);
   
   </span><span>class</span><span> ServerSocket {
        </span><span>private</span> <span>$server_host</span>;  <span>//</span><span>服务器IP</span>
     <span>private</span> <span>$server_port</span>;  <span>//</span><span>服务器端口</span>
     <span>private</span> <span>$client_host</span>;  <span>//</span><span>客户端IP</span>
     <span>private</span> <span>$client_port</span>;  <span>//</span><span>客户端端口</span>
     <span>private</span> <span>$create_socket</span>=<span>null</span><span>;   
     </span><span>private</span> <span>$accept_socket</span>=<span>null</span><span>;
     </span><span>private</span> <span>$get_data</span>=""<span>;
     </span><span>private</span> <span>$send_data</span>=""<span>;    
     
     </span><span>//</span><span>够造函数</span>
     <span>public</span> <span>function</span> __construct(<span>$host</span>,<span>$port</span><span>){
         </span><span>if</span>(!<span>extension_loaded</span>("socket"<span>)){
             </span><span>exit</span>("请先打开socket扩展!"<span>);
         }
         </span><span>if</span>(<span>empty</span>(<span>$host</span><span>)) 
             </span><span>exit</span>("请输入目标主机IP!"<span>);
         </span><span>if</span>(<span>empty</span>(<span>$port</span><span>))
             </span><span>exit</span>("请输入有效端口号!"<span>);
         </span><span>$this</span>->server_host=<span>$host</span><span>;
         </span><span>$this</span>->server_port=<span>$port</span><span>;
         </span><span>$this</span>-><span>CreateSocket();
     }
     
     </span><span>//</span><span>创建一个socket并将其用来绑定监听端口</span>
     <span>private</span> <span>function</span><span> createSocket(){
           </span><span>if</span>(<span>$this</span>->create_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)==<span>false</span><span>){
                 </span><span>echo</span> "socket_create() failed. reason:".socket_strerror(socket_last_error())."\n"<span>;
           }
           </span><span>if</span>(socket_bind(<span>$this</span>->create_socket,<span>$this</span>->server_host,<span>$this</span>->server_port)==<span>false</span><span>){
               </span><span>echo</span> "socket_bind()failed. reason:".socket_strerror(socket_last_error(<span>$this</span>->create_socket))."\n"<span>;
           }
           </span><span>if</span>(socket_listen(<span>$this</span>->create_socket,5)==<span>false</span><span>){
               </span><span>echo</span> "socket_listen()failed. reason:".socket_strerror(socket_last_error(<span>$this</span>->create_socket))."\n"<span>;
           }        
     }
     
     </span><span>//</span><span>向目标主机发起连接</span>
     <span>public</span> <span>function</span><span> connectClient(){
         </span><span>if</span>(socket_getpeername(<span>$this</span>->create_socket,<span>$this</span>->client_host,<span>$this</span>->client_port)==<span>null</span><span>){
             </span><span>echo</span> "socket_getpeername()failed. reason:".socket_strerror(socket_last_error(<span>$this</span>->create_socket))."\n"<span>;
         }
         </span><span>if</span>(socket_connect(<span>$this</span>->create_socket,<span>$this</span>->client_host,<span>$this</span>->client_port)==<span>false</span><span>){
             </span><span>echo</span> "socket_connect()failed. reason:".socket_strerror(socket_last_error(<span>$this</span>->create_socket))."\n"<span>;
         }
     }
     </span><span>//</span><span>接受连接获取到一个socket资源,想客户端读取以及传输信息</span>
     <span>public</span> <span>function</span><span> wr(){
         </span><span>do</span>{   <span>//</span><span>循环防止阻塞延迟</span>
             <span>if</span>(<span>$this</span>->accept_socket=socket_accept(<span>$this</span>->create_socket)==<span>null</span><span>){
                 </span><span>echo</span> "socket_accept()failed. reason:".socket_strerror(socket_last_error(<span>$this</span>->create_socket))."\n"<span>;
                 </span><span>break</span><span>;
             }
             
             </span><span>$this</span>->get_data = socket_read(<span>$this</span>->accept_socket, 8192<span>);
             </span><span>$this</span>->send_data=<span>$this</span>->operateData(<span>$this</span>-><span>get_data);
             </span><span>if</span> (socket_write(<span>$this</span>->accept_socket,<span>$this</span>->send_data, <span>strlen</span>(<span>$this</span>->send_data))==<span>false</span><span>) {
                 </span><span>echo</span> "socket_write() failed reason:" . socket_strerror(socket_last_error(<span>$this</span>->accept_socket)) ."\n"<span>;
             }
             socket_close(</span><span>$this</span>-><span>accept_socket);
         }</span><span>while</span>(<span>true</span><span>);          
     }
     
     </span><span>//</span><span>数据处理</span>
     <span>private</span> <span>function</span><span> operateData(){
         
         </span><span>return</span><span> ;
     }
     
     </span><span>//</span><span>关闭监听socket</span>
     <span>private</span> <span>function</span><span> closeSocket(){
         socket_close(</span><span>$this</span>-><span>createSocket);
     }
     
     </span><span>//</span><span>析构函数</span>
     <span>public</span> <span>function</span><span>  __destruct(){
          </span><span>$this</span>-><span>closeSocket();
     }
   }
  
   
   </span>
로그인 후 복사
<span>//</span><span>ClientSocket.class.php
//客户端socke操作类</span>

<span>class</span><span> Socket {
    </span><span>private</span> <span>$host</span>;<span>//</span><span>连接socket的主机</span>
    <span>private</span> <span>$port</span>;<span>//</span><span>socket的端口号 </span>
    <span>private</span> <span>$error</span>=<span>array</span><span>();
    </span><span>private</span> <span>$socket</span>=<span>null</span>;<span>//</span><span>socket的连接标识</span>
    <span>private</span> <span>$queryStr</span>="";<span>//</span><span>发送的数据</span>
    <span>public</span> <span>function</span> __construct(<span>$host</span>,<span>$port</span><span>) {
        </span><span>if</span>(!<span>extension_loaded</span>("sockets"<span>)){
            </span><span>exit</span>("请打开socket扩展 "<span>);
        }
        </span><span>if</span>(<span>empty</span>(<span>$host</span>)) <span>exit</span>("请输入目标地址"<span>);
        </span><span>if</span>(<span>empty</span>(<span>$port</span>)) <span>exit</span>("请输入有效的端口号"<span>);
        </span><span>$this</span>->host=<span>$host</span><span>;
        </span><span>$this</span>->port=<span>$port</span><span>;
        </span><span>$this</span>->CreateSocket();<span>//</span><span>创建连接        </span>
<span>    }

    </span><span>//</span><span>创建socket</span>
    <span>private</span> <span>function</span><span> CreateSocket(){
        </span>!<span>$this</span>->socket&&<span>$this</span>->socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);<span>//</span><span>创建socket</span>
        <span>$r</span>=@socket_connect(<span>$this</span>->socket,<span>$this</span>->host,<span>$this</span>-><span>port);
        </span><span>if</span>(<span>$r</span><span>){
            </span><span>return</span> <span>$r</span><span>;
        }</span><span>else</span><span>{
            </span><span>$this</span>->error[]=socket_last_error(<span>$this</span>-><span>socket);
            </span><span>return</span> <span>false</span><span>;
        }
    }

    </span><span>//</span><span>向socket服务器写入数据并读取</span>
    <span>public</span> <span>function</span> wr(<span>$contents</span><span>){
        </span><span>$this</span>->queryStr=""<span>;
        </span><span>$this</span>->queryStr=<span>$contents</span><span>;
        </span>!<span>$this</span>->socket&&<span>$this</span>-><span>CreateSocket();
        </span><span>$contents</span>=<span>$this</span>->fliterSendData(<span>$contents</span><span>);
        </span><span>$result</span>=socket_write(<span>$this</span>->socket,<span>$contents</span>,<span>strlen</span>(<span>$contents</span><span>));
        </span><span>if</span>(!<span>intval</span>(<span>$result</span><span>)){
            </span><span>$this</span>->error[]=socket_last_error(<span>$this</span>-><span>socket);
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>$response</span>=socket_read(<span>$this</span>->socket,12048<span>);
        </span><span>if</span>(<span>false</span>===<span>$response</span><span>){
            </span><span>$this</span>->error[]=socket_last_error(<span>$this</span>-><span>socket);
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>return</span> <span>$response</span><span>;
    }

    </span><span>//</span><span>对发送的数据进行过滤</span>
    <span>private</span> <span>function</span> fliterSendData(<span>$contents</span><span>){
        </span><span>//</span><span>对写入的数据进行处理</span>
        <span>return</span> <span>$contents</span><span>;
    }

    </span><span>//</span><span>所有错误信息 </span>
    <span>public</span> <span>function</span><span> getError(){
        </span><span>return</span> <span>$this</span>-><span>error;
    }

    </span><span>//</span><span>最后一次错误信息</span>
    <span>public</span> <span>function</span><span> getLastError(){
        </span><span>return</span> <span>$this</span>->error(<span>count</span>(<span>$this</span>-><span>error));
    }
    
    </span><span>//</span><span>获取最后一次发送的消息</span>
    <span>public</span> <span>function</span><span> getLastMsg(){
        </span><span>return</span> <span>$this</span>-><span>queryStr;
    }

    </span><span>public</span> <span>function</span><span> getHost(){
        </span><span>return</span> <span>$this</span>-><span>host;
    }

    </span><span>public</span> <span>function</span><span> getPort(){
        </span><span>return</span> <span>$this</span>-><span>port;
    }

    </span><span>//</span><span>关闭socket连接</span>
    <span>private</span> <span>function</span><span> close(){
        </span><span>$this</span>->socket&&socket_close(<span>$this</span>->socket);<span>//</span><span>关闭连接</span>
        <span>$this</span>->socket=<span>null</span>;<span>//</span><span>连接资源初始化</span>
<span>    }

    </span><span>public</span> <span>function</span><span> __destruct(){
        </span><span>$this</span>-><span>close();
    }
}</span>
로그인 후 복사

 

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿