Thinkphp Socket.class.php 类的使用

未结帖
1 7476
ajian lucy 2017-01-12
悬赏:5飞吻
public function socket_client()
{
    import('ORG.Util.Socket');// 导入socket类
    $confing = array(
        'persistent' => false,
        'host' => '127.0.0.1',
        'protocol' => 'tcp',
        'port' => 10005,
        'timeout' => 1800
    );
    $Socket = new Socket($confing);

    if ($Socket->connect()) {
        echo "TP类 创建Socket链接成功!<hr>";
    } else {
        echo "TP类 创建Socket链接失败!<hr>";
    }
    $data = "我是客户端,我要发数据给服务端";
    $Socket->write($data);
    $read = $Socket->read();
    //$read 是服务端还回的数据
    echo $read . "<hr >";
    $Socket->disconnect();

}


public function socket_server()
{
    //报错级别

    error_reporting(E_ALL);

    //设置长链接

    set_time_limit(0);

    //ip

    $address = "127.0.0.1";

    //端口

    $port = 10005;

    //创建一个套接字

    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {

        echo "创建一个套接字 失败" . "\n";

    }

    //启动套接字

    if (socket_bind($sock, $address, $port) === false) {

        echo "启动套接字 失败
        " . socket_strerror(socket_last_error($sock)) . "\n";

    }


    //监听端口

    if (socket_listen($sock, 5) === false) {

        echo "监听端口 失败
        " . socket_strerror(socket_last_error($sock)) . "\n";

    }


    do {

        //似乎是接收客户端传来的消息

        if (($msgsock = socket_accept($sock)) === false) {

            echo "socket_accepty() failed :
            reason:" . socket_strerror(socket_last_error($sock)) . "\n";

            break;

        }

        //echo "读取客户端传来的消息"."\n";

        $buf = socket_read($msgsock, 8192);

        $talkback = "我已经成功接到客户端的信息了。现在我还回信息给客户端" . "\n";

        if (false === socket_write($msgsock, $talkback)) {

            echo "socket_write() failed reason
            :" . socket_strerror(socket_last_error($sock)) . "\n";

        } else {

            echo "return info msg ku fu duan success" . "\n";

        }

        socket_close($msgsock);

    } while (true);

    socket_close($sock);


}


热忱回答1


最近热帖

近期热议

  1. javascript——prototype与__proto 9
  2. Mysql 中出现的Data truncated for column 3
  3. 在nginx中使用x-sendfile的解决方案 3
  4. 高版本jQuery面插件实现Ajax上传图片 1
  5. Thinkphp Socket.class.php 类的使用 1
  6. 使用ionic3创建第一个App 0
  7. ios-oc html5 0
  8. nginx.conf 0
  9. 基于ionic3.4.0的项目搭建 0
  10. php 缩略图 0