一个PHP Socket类

写的一个PHP Socket类,功能还比较简单,不完善.

<? php
/** */ /** *
     * @project:socket类
     * @license:GPL
     * 
@author : 8th@live.cn-星期八
     * @description:PHP Socket协议异步通信
     * @file:socket.class.php
     * @created date:Fri Apr 25 12:22:33 CST 2008
     * @last modified :
     **
*/

class  sockets
{
    
public  $host; // 通信地址
     public  $port; // 通信端口
     public  $limitTime = 0 ; // 连接超时时间
     public  $backlog = 3 ; // 请求队列中允许的最大请求数
     private  $socket = null ;
    
private  $result = null ;
    
private  $spawn = null ;
    
private  $input = null ;
    
// 构造函数
     public  function __construct()
    
{
        set_time_limit($
this -> limitTime);
        $
this -> socket  =  socket_create(AF_INET, SOCK_STREAM,  0 ) or die( " Could not create socket\n " );
    }

    
// 创建Socket连接,监听外部连接
     public  function socket_bind_listen()
    
{
        $
this -> result  =  socket_bind($ this -> socket, $ this -> host, $ this -> port) or die( " Could not bind to socket\n " );
        $
this -> result  =  socket_listen($ this -> socket, $ this -> backlog) or die( " Could not set up socket listener\n " );
    }

    
// 接受请求连接,调用socket处理信息
     public  function accept_client()
    
{
        $
this -> spawn  =  socket_accept($ this -> socket) or die( " Could not accept incoming connection\n " );
        $msg 
=   " Welcome to the Test Server " ;
        socket_write($
this -> spawn, $msg, strlen($msg));
    }

    
//  读取客户端输入 
     public  function read_client()
    
{
        $
this -> input  =  socket_read($ this -> spawn,  2048 , PHP_NORMAL_READ) or die( " Could not read input\n " ); 
    }

    
//  处理客户端输入并返回数据 
     public  function write_client()
    
{
        socket_write($
this -> spawn, $ this -> input, strlen ($ this -> input)) or die( " Could not write output\n " );
    }

    
// 析构函数
     public  function __destruct()
    
{
        socket_close($
this -> spawn); 
        socket_close($
this -> socket); 
    }

}

/** */ /** *
$socket_test=new sockets();
$socket_test->host="192.168.0.2";
$socket_test->port="13654";
$socket_test->socket_bind_listen();
$socket_test->accept_client();
$socket_test->read_client();
$socket_test->write_client();
     **
*/

?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值