PHP 操作socket 实现简易聊天室

<?php

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

socket_bind($socket ,'127.0.0.1', 11211 );

socket_listen( $socket ,5);

while( true ){

    $con = socket_accept( $socket );

    if( $con !==false ){

        socket_write($con, 'init', 4 );

        while(  $str = socket_read( $con,1024 ) ){

            echo 'client:'.$str."\n";

            $ret = fgets(STDIN);

        }

        socket_close( $con );

    }

}

service.php ↑

 

<?php

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

socket_connect( $socket ,'127.0.0.1', 11211 );

while( $t = socket_read( $socket,1024  ) ){

    echo 'server:'.$t."\n";

    $str = trim(fgets(STDIN));

    if( $str ){

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

    }

}

socket_close( $socket );

client.php ↑

 

工作在cli模式下。。。

你可能感兴趣的:(socket)