123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517 |
- <?php
- namespace Mall\Framework\Swoole;
- use Mall\Framework\Swoole\WebsocketClient\Parser;
- use Mall\Framework\Swoole\WebsocketClient\WebsocketParser;
- class WebSocketClient
- {
- const VERSION = '0.1.4';
- const TOKEN_LENGHT = 16;
- const TYPE_ID_WELCOME = 0;
- const TYPE_ID_PREFIX = 1;
- const TYPE_ID_CALL = 2;
- const TYPE_ID_CALLRESULT = 3;
- const TYPE_ID_ERROR = 4;
- const TYPE_ID_SUBSCRIBE = 5;
- const TYPE_ID_UNSUBSCRIBE = 6;
- const TYPE_ID_PUBLISH = 7;
- const TYPE_ID_EVENT = 8;
- protected $key;
- protected $host;
- protected $port;
- protected $path;
-
- protected $socket;
- protected $buffer = '';
-
- protected $connected = false;
- protected $handshake = false;
- protected $ssl = false;
- protected $ssl_key_file;
- protected $ssl_cert_file;
- protected $haveSwooleEncoder = false;
- protected $header;
- const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
- const UserAgent = 'SwooleWebsocketClient';
-
- function __construct($options, $path = '/')
- {
- if (empty($options))
- {
- throw new \Exception("联系webstock服务端配置为空");
- }
- $this->haveSwooleEncoder = method_exists('swoole_websocket_server', 'pack');
- $this->host = $options['host'];
- $this->port = $options['port'];
- $this->path = $path;
- $this->key = $this->generateToken(self::TOKEN_LENGHT);
- $this->parser = new WebsocketParser();
- if($options['ssl'] == true){
- self::enableCrypto($options['ssl_key_file'], $options['ssl_cert_file']);
- }
- if(!self::connect(isset($options['time_out'])?$options['time_out']:0.5)){
- throw new \Exception("connect failed. Error:".$this->socket->errCode.PHP_EOL);
- }
- }
-
- function enableCrypto($keyFile = '', $certFile = '')
- {
- if (!extension_loaded('swoole'))
- {
- throw new \Exception("require swoole extension.");
- }
- $this->ssl = true;
- $this->ssl_key_file = $keyFile;
- $this->ssl_cert_file = $certFile;
- }
-
- function __destruct()
- {
- if ($this->connected)
- {
- $this->disconnect();
- }
- }
-
- public function connect($timeout = 0.5)
- {
- if (extension_loaded('swoole'))
- {
- $type = SWOOLE_TCP;
- if ($this->ssl)
- {
- $type |= SWOOLE_SSL;
- }
- $this->socket = new \swoole_client($type);
- if ($this->ssl_key_file)
- {
- $this->socket->set(array(
- 'ssl_key_file' => $this->ssl_key_file,
- 'ssl_cert_file' => $this->ssl_cert_file,
-
- ));
- }
- }
- else
- {
- $this->socket = new \TCP;
- }
-
- if (!$this->socket->connect($this->host, $this->port, $timeout))
- {
- return false;
- }
- $this->connected = true;
-
- if ($this->socket->send($this->createHeader()) === false)
- {
- return false;
- }
- $headerBuffer = '';
- while(true)
- {
- $_tmp = $this->socket->recv();
- if ($_tmp)
- {
- $headerBuffer .= $_tmp;
- if (substr($headerBuffer, -4, 4) != "\r\n\r\n")
- {
- continue;
- }
- }
- else
- {
- return false;
- }
- return $this->doHandShake($headerBuffer);
- }
- return false;
- }
-
- function doHandShake($headerBuffer)
- {
- $header = Parser::parseHeader($headerBuffer);
- if (!isset($header['Sec-WebSocket-Accept']))
- {
- $this->disconnect();
- return false;
- }
- if ($header['Sec-WebSocket-Accept'] != base64_encode(pack('H*', sha1($this->key . self::GUID))))
- {
- $this->disconnect();
- return false;
- }
- $this->handshake = true;
- $this->header = $header;
- return true;
- }
-
- public function disconnect()
- {
- $this->connected = false;
- $this->socket->close();
- }
-
- function recv()
- {
- if (!$this->handshake)
- {
- trigger_error("not complete handshake.");
- return false;
- }
- while (true)
- {
- $data = $this->socket->recv();
- if (!$data)
- {
- return false;
- }
- $this->parser->push($data);
- $frame = $this->parser->pop($data);
- if ($frame)
- {
- return $frame->data;
- }
- }
- return false;
- }
-
- public function send($data, $type = 'text', $masked = true)
- {
- if (empty($data))
- {
- throw new \Exception("data is empty");
- }
- if (!$this->handshake)
- {
- trigger_error("not complete handshake.");
- return false;
- }
- if ($this->haveSwooleEncoder)
- {
- switch($type)
- {
- case 'text':
- $_type = WEBSOCKET_OPCODE_TEXT;
- break;
- case 'binary':
- case 'bin':
- $_type = WEBSOCKET_OPCODE_BINARY;
- break;
- default:
- return false;
- }
- $_send = \swoole_websocket_server::pack($data, $_type);
- }
- else
- {
- $_send = $this->hybi10Encode($data, $type, $masked);
- }
- return $this->socket->send($_send);
- }
-
- function sendJson($data, $masked = true)
- {
- return $this->send(json_encode($data, JSON_UNESCAPED_UNICODE).PACKAGE_EOF, 'text', $masked);
- }
-
- final protected function createHeader()
- {
- $host = $this->host;
- if ($host === '127.0.0.1' || $host === '0.0.0.0')
- {
- $host = 'localhost';
- }
- return "GET {$this->path} HTTP/1.1" . "\r\n" .
- "Origin: null" . "\r\n" .
- "Host: {$host}:{$this->port}" . "\r\n" .
- "Sec-WebSocket-Key: {$this->key}" . "\r\n" .
- "User-Agent: ".self::UserAgent."/" . self::VERSION . "\r\n" .
- "Upgrade: Websocket" . "\r\n" .
- "Connection: Upgrade" . "\r\n" .
- "Sec-WebSocket-Protocol: wamp" . "\r\n" .
- "Sec-WebSocket-Version: 13" . "\r\n" . "\r\n";
- }
-
- final protected function parseIncomingRaw($header)
- {
- $retval = array();
- $content = "";
- $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
- foreach ($fields as $field) {
- if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
- $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function ($matches) {
- return strtoupper($matches[0]);
- }, strtolower(trim($match[1])));
- if (isset($retval[$match[1]])) {
- $retval[$match[1]] = array($retval[$match[1]], $match[2]);
- } else {
- $retval[$match[1]] = trim($match[2]);
- }
- } else if (preg_match('!HTTP/1\.\d (\d)* .!', $field)) {
- $retval["status"] = $field;
- } else {
- $content .= $field . "\r\n";
- }
- }
- $retval['content'] = $content;
- return $retval;
- }
-
- private function generateToken($length)
- {
- $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
- $useChars = array();
-
- for ($i = 0; $i < $length; $i++) {
- $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
- }
-
- array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
- shuffle($useChars);
- $randomString = trim(implode('', $useChars));
- $randomString = substr($randomString, 0, self::TOKEN_LENGHT);
- return base64_encode($randomString);
- }
-
- public function generateAlphaNumToken($length)
- {
- $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
- srand((float)microtime() * 1000000);
- $token = '';
- do
- {
- shuffle($characters);
- $token .= $characters[mt_rand(0, (count($characters) - 1))];
- } while (strlen($token) < $length);
- return $token;
- }
-
- private function hybi10Encode($payload, $type = 'text', $masked = true)
- {
- $frameHead = array();
- $payloadLength = strlen($payload);
- switch ($type)
- {
-
- case 'text':
-
- $frameHead[0] = 129;
- break;
-
- case 'binary':
- case 'bin':
-
- $frameHead[0] = 130;
- break;
- case 'close':
-
- $frameHead[0] = 136;
- break;
- case 'ping':
-
- $frameHead[0] = 137;
- break;
- case 'pong':
-
- $frameHead[0] = 138;
- break;
- }
-
- if ($payloadLength > 65535)
- {
- $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
- $frameHead[1] = ($masked === true) ? 255 : 127;
- for ($i = 0; $i < 8; $i++)
- {
- $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
- }
-
- if ($frameHead[2] > 127)
- {
- $this->socket->close();
- return false;
- }
- }
- elseif ($payloadLength > 125)
- {
- $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
- $frameHead[1] = ($masked === true) ? 254 : 126;
- $frameHead[2] = bindec($payloadLengthBin[0]);
- $frameHead[3] = bindec($payloadLengthBin[1]);
- }
- else
- {
- $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
- }
-
- foreach (array_keys($frameHead) as $i)
- {
- $frameHead[$i] = chr($frameHead[$i]);
- }
-
- $mask = array();
- if ($masked === true)
- {
- for ($i = 0; $i < 4; $i++)
- {
- $mask[$i] = chr(rand(0, 255));
- }
- $frameHead = array_merge($frameHead, $mask);
- }
- $frame = implode('', $frameHead);
-
- for ($i = 0; $i < $payloadLength; $i++)
- {
- $frame .= $masked ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
- }
- return $frame;
- }
-
- private function hybi10Decode($data)
- {
- if (empty($data))
- {
- throw new \Exception("data is empty");
- }
- $bytes = $data;
- $secondByte = sprintf('%08b', ord($bytes[1]));
- $masked = ($secondByte[0] == '1') ? true : false;
- $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
-
- if ($dataLength === 126)
- {
- $decodedData = substr($bytes, 4);
- }
- elseif ($dataLength === 127)
- {
- $decodedData = substr($bytes, 10);
- }
- else
- {
- $decodedData = substr($bytes, 2);
- }
- exit("len=".$dataLength."\n");
- return $decodedData;
- }
- }
|