【问题标题】:php open 2 tcp socketphp打开2个tcp套接字
【发布时间】:2016-10-26 08:49:09
【问题描述】:

当我在 php 中打开 2 个不同的套接字时,我首先得到不同的资源 id,但在打开下一个套接字后,得到相同的资源 id。 下面是连接三个不同socket的结果

# ./test.php

127.0.0.1:26379/132458106d92e8f7b 127.0.0.1:26379 - 资源 ID #8 127.0.0.1:6380/320458106d92e906e 127.0.0.1:6380 - 资源 ID #9 127.0.0.1:6381/102858106d92e9106 127.0.0.1:6381 - 资源 ID #10 资源 ID #10Array ( [超时] => [阻塞] => 1 [eof] => [stream_type] => tcp_socket/ssl [模式] => r+ [未读字节] => 0 [可搜索] => )

资源 id #10Array ( [超时] => [阻塞] => 1 [eof] => [stream_type] => tcp_socket/ssl [模式] => r+ [未读字节] => 0 [可搜索] => )

资源 id #10Array ( [超时] => [阻塞] => 1 [eof] => [stream_type] => tcp_socket/ssl [模式] => r+ [未读字节] => 0 [可搜索] => )

我使用下面的代码:

class RedisClient    
function __construct ($arr = array ())
    {
        if (count($arr) === 0) return FALSE;

        self::$host = $arr[0];
        self::$port = $arr[1];
        self::$persistent = '/' . uniqid(rand(100,10000));

        self::$fp =
            stream_socket_client('tcp://'.self::$host . ':' .
                                 self::$port .
                                 self::$persistent, $errno, $errstr, self::$connect_timeout, self::$flags);

        echo self::$host,':',self::$port,self::$persistent,PHP_EOL;

        if (!self::$fp) {
            echo "$errstr ($errno)" . PHP_EOL;

            return FALSE;
        }

        echo self::$host,':',self::$port,' - ';
        print_r(self::$fp);
        echo PHP_EOL;

        if (!stream_set_timeout(self::$fp, self::$timeout)) return FALSE;

    }

function getMeta ()
    {
        print_r (self::$fp);
        print_r (stream_get_meta_data(self::$fp));
        return;
    }

$c=new RedisClient(array('127.0.0.1',26379));

$m=new RedisClient(array('127.0.0.1',6380));

$s=new RedisClient(array('127.0.0.1',6381));

$c->getMeta();
echo PHP_EOL;
$m->getMeta();
echo PHP_EOL;
$s->getMeta();
echo PHP_EOL;

exit;

任何人都知道,为什么在所有套接字连接之后,所有资源 id 都是相同的? 以及如何让它与众不同?

【问题讨论】:

  • 我认为在非静态上下文中使用静态变量会产生警告或通知。你不应该以这种方式混合上下文,但也要在类中声明你的变量。

标签: php sockets websocket


【解决方案1】:

你使用了 self::$fp (静态变量),你需要在类中使用 $this 来按对象获取不同的变量。

"self::$var = 1;" - 为类创建一个变量(无对象)

"$this->var = 1;" - 在对象中创建属性

例如你可以写:

class Test {
   protected $a = 1;
   protected static $b = 1;
   public function incA()
   {
       $this->a++;
   }
   public static function incB()
   {
       self::$b++;
   }
   public function getA()
   {
       return $this->a;
   }
   public static function getB()
   {
       return self::$b;
   }
}
$test = new Test();
$test->incA();
$test->incA();
var_dump($test->getA());
var_dump(Test::getB()); // or $test::getB();

Test::incB();
$test2 = new Test();
var_dump($test2->getA());
var_dump($test2::getB());
var_dump($test::getB());
var_dump(Test::getB());

Read more here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2016-08-03
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多