PHP实现Socket通讯

PHP实现Socket通讯

1. 客户端


$host = gethostbyname('www.sina.cn');

$port = 80;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_connect($socket, $host, $port);

$send = "HEAD / HTTP/1.1\r\nHost: www.sina.cn\r\nConnection: Close\r\n\r\n";

socket_write($socket, $send, strlen($send));

$result = '';

while( True ){
    $bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL);
    if(empty($buf)){
        break;
    }else{
        $result .= $buf;
    }
}

socket_close($socket);

echo $result;

2. 服务端


set_time_limit(0);

$address = '127.0.0.1';

$port = 9999;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if( $sock === false) {
    echo "socket_create() failed : " . socket_strerror(socket_last_error()) . "\n";
}else{

    if (socket_bind($sock, $address, $port) === false) {
        echo "socket_bind() failed : " . socket_strerror(socket_last_error($sock)) . "\n";
    }else{

        if (socket_listen($sock, 5) === false) {
            echo "socket_bind() failed : " . socket_strerror(socket_last_error($sock)) . "\n";
        }

        while(true){

            $msgsock = socket_accept($sock);

            if ($msgsock === false) {
                echo "socket_accepty() failed : ".socket_strerror(socket_last_error($sock)) . "\n";
            }else{
                $msg = "<font color='red'>server send:welcome</font><br/>";
                socket_write($msgsock, $msg, strlen($msg));
                $buf = socket_read($msgsock, 8192);
                $talkback = "received message:$buf\n";
                if (false === socket_write($msgsock, $talkback, strlen($talkback))) {
                    echo "socket_write() failed : " . socket_strerror(socket_last_error($sock)) ."\n";
                }
            }

            socket_close($msgsock);

        };

    }
}

//关闭socket
socket_close($sock);