PHP 操作socket 实现简易聊天室

时间:2021-07-25 13:18:40
<?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模式下。。。