소스 검색

Adding support of custom functions within protocols.
Adding support of WebSocket subprotocols for WebSocket client.

Usage example:

$worker->onWorkerStart = function() {
$ws = new AsyncTcpConnection("ws://192.168.1.16:1884/");
$ws->WSSetProtocol('mqtt');
$ws->onWebSocketConnect = function($conn) {
echo "WebSocketConnection is set, server protocol is: [".$conn->WSGetServerProtocol()."]\n";
};

Vitaliy Ponomarev 8 년 전
부모
커밋
796c413d0e
2개의 변경된 파일45개의 추가작업 그리고 0개의 파일을 삭제
  1. 25 0
      Connection/TcpConnection.php
  2. 20 0
      Protocols/Ws.php

+ 25 - 0
Connection/TcpConnection.php

@@ -254,6 +254,31 @@ class TcpConnection extends ConnectionInterface
         self::STATUS_CLOSED      => 'CLOSED',
     );
 
+
+    /**
+     * Adding support of custom functions within protocols
+     *
+     * @param string $name
+     * @param array  $arguments
+     */
+    public function __call($name, $arguments) {
+        // Try to emit custom function within protocol
+        if (method_exists($this->protocol, $name)) {
+            try {
+                return call_user_func(array($this->protocol, $name), $this, $arguments);
+            } catch (\Exception $e) {
+                Worker::log($e);
+                exit(250);
+            } catch (\Error $e) {
+                Worker::log($e);
+                exit(250);
+            }
+	} else {
+	    trigger_error('Call to undefined method '.__CLASS__.'::'.$name.'()', E_USER_ERROR);
+	}
+
+    }
+
     /**
      * Construct.
      *

+ 20 - 0
Protocols/Ws.php

@@ -374,6 +374,7 @@ class Ws
         "Connection: Upgrade\r\n".
         "Upgrade: websocket\r\n".
         "Origin: ". (isset($connection->websocketOrigin) ? $connection->websocketOrigin : '*') ."\r\n".
+	(isset($connection->WSClientProtocol)?"Sec-WebSocket-Protocol: ".$connection->WSClientProtocol."\r\n":'').
         "Sec-WebSocket-Version: 13\r\n".
         "Sec-WebSocket-Key: " . base64_encode(md5(mt_rand(), true)) . "\r\n\r\n";
         $connection->send($header, true);
@@ -395,6 +396,16 @@ class Ws
         $pos = strpos($buffer, "\r\n\r\n");
         if ($pos) {
             // handshake complete
+
+	    // Get WebSocket subprotocol (if specified by server)
+    	    $header = explode("\r\n", substr($buffer, 0, $pos));
+	    foreach ($header as $hrow) {
+		if (preg_match("#^(.+?)\:(.+?)$#", $hrow, $m) && ($m[1] == "Sec-WebSocket-Protocol")) {
+		    $connection->WSServerProtocol = trim($m[2]);
+		}
+
+	    }
+
             $connection->handshakeStep = 2;
             $handshake_response_length = $pos + 4;
             // Try to emit onWebSocketConnect callback.
@@ -430,4 +441,13 @@ class Ws
         }
         return 0;
     }
+
+    public static function WSSetProtocol($connection, $params) {
+	$connection->WSClientProtocol = $params[0];
+    }
+
+    public static function WSGetServerProtocol($connection) {
+	return (property_exists($connection, 'WSServerProtocol')?$connection->WSServerProtocol:null);
+    }
+
 }