10 public function __construct($peer)
16 $reflect = new \ReflectionClass($peer);
17 foreach ($reflect->getConstants() as $name => $value) {
18 if (!strncmp($name,
'OP_', 3)) {
19 $opcodes[ord($value)] = (string) substr($name, 3);
22 $this->opcodes = $opcodes;
25 protected function send($op, $data =
'')
28 if (strlen($data) > 65535) {
29 throw new \RuntimeException();
34 $data = $op . pack(
'n', strlen($data)) . $data;
37 while ($written < $len) {
38 $wrote = @fwrite($this->socket, substr($data, $written));
39 if ($wrote ===
false) {
40 throw \RuntimeException();
47 protected function receive()
51 while (($len = strlen($res)) != 3) {
52 $read = @fread($this->socket, 3 - $len);
53 if (feof($this->socket)) {
54 throw new \RuntimeException();
56 if ($read !==
false) {
60 list($op, $dataLen) = array_values(unpack(
'cop/ndata', $res));
64 while (($len = strlen($data)) != $dataLen) {
65 $read = @fread($this->socket, $dataLen - $len);
66 if (feof($this->socket)) {
67 throw new \RuntimeException();
69 if ($read !==
false) {
74 return array($op, $data);
77 public function runOnce()
80 list($op, $data) = $this->receive();
83 if (!isset($this->opcodes[$op])) {
84 throw new \RuntimeException();
88 $handler =
'handle' . $this->opcodes[$op];
89 if (method_exists($this, $handler)) {
90 return call_user_func(array($this, $handler), $data);