PHP SOCKET编程(未完)

一个简单TCP/IP的例子

服务端

<?php
//declare (strict_types = 1);
//https://www.php.net/manual/zh/function.stream-socket-server.php

$socket_server = stream_socket_server("tcp://0.0.0.0:8848",$errno,$errstr);
if(!$socket_server){
    echo "$errstr ($errno)<br />\n";exit;
}

while (true){
    $buffer = '';
    $client = stream_socket_accept($socket_server);
    print "accepted " . stream_socket_get_name( $client, true) . "\n";
    if($client){
        // Read until double CRLF # 读取客户端发来数据
        $buffer = fread($client, 2048); 

        echo "客户端发来的数据:".$buffer;

        // Respond to client # 响应客户端数据
        fwrite($client,  "200 OK HTTP/1.1\r\n"
            . "Connection: close\r\n"
            . "Content-Type: text/html\r\n"
            . "\r\n"
            . "Hello World! " . microtime(true)
            . "<pre>{$buffer}</pre>");

        fclose($client);

    }

}

 

 

客户端

 

<?php
//declare (strict_types = 1);

//https://www.php.net/manual/zh/function.stream-socket-server.php
$fp = stream_socket_client("tcp://127.0.0.1:8848", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {

    //发送给服务器的数据
    fwrite($fp, "Aloha");

    //打印服务返回的数据
    while (!feof($fp)) {
        var_dump(fgets($fp, 1024));
    }
    fclose($fp);
}

 

 

 

https://www.php.net/manual/zh/function.stream-socket-server.php

转 http://blog.csdn.net/hguisu/article/details/7448528

posted @ 2017-11-20 00:21  与f  阅读(117)  评论(0编辑  收藏  举报