浏览代码

handshake automatically as ws client for issue #78

walkor 9 年之前
父节点
当前提交
6ad21a37e4
共有 2 个文件被更改,包括 25 次插入1 次删除
  1. 11 0
      Connection/AsyncTcpConnection.php
  2. 14 1
      Protocols/Ws.php

+ 11 - 0
Connection/AsyncTcpConnection.php

@@ -196,6 +196,17 @@ class AsyncTcpConnection extends TcpConnection
             }
             $this->_status        = self::STATUS_ESTABLISH;
             $this->_remoteAddress = stream_socket_get_name($socket, true);
+            if (is_callable(array($this->protocol, 'onConnect'))) {
+                try {
+                    call_user_func(array($this->protocol, 'onConnect'), $this);
+                } catch (\Exception $e) {
+                    Worker::log($e);
+                    exit(250);
+                } catch (\Error $e) {
+                    Worker::log($e);
+                    exit(250);
+                }
+            }
             // Try to emit onConnect callback.
             if ($this->onConnect) {
                 try {

+ 14 - 1
Protocols/Ws.php

@@ -275,6 +275,16 @@ class Ws
     }
 
     /**
+     * Send websocket handshake data.
+     *
+     * @return void
+     */
+    public static function onConnect($connection)
+    {
+        self::sendHandshake($connection);
+    }
+
+    /**
      * Send websocket handshake.
      *
      * @param \Workerman\Connection\TcpConnection $connection
@@ -282,6 +292,9 @@ class Ws
      */
     public static function sendHandshake($connection)
     {
+        if (!empty($connection->handshakeStep)) {
+            return;
+        }
         // Get Host.
         $port = $connection->getRemotePort();
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
@@ -296,7 +309,7 @@ class Ws
         $connection->send($header, true);
         $connection->handshakeStep               = 1;
         $connection->websocketCurrentFrameLength = 0;
-        $connection->websocketDataBuffer  = '';
+        $connection->websocketDataBuffer         = '';
         if (empty($connection->websocketType)) {
             $connection->websocketType = self::BINARY_TYPE_BLOB;
         }