WebsocketClient.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: phperstar
  5. * Date: 2020/11/6
  6. * Time: 10:22 AM
  7. */
  8. namespace Mall\Framework\Swoole;
  9. use Mall\Framework\Swoole\WebsocketClient\Parser;
  10. use Mall\Framework\Swoole\WebsocketClient\WebsocketParser;
  11. class WebSocketClient
  12. {
  13. const VERSION = '0.1.4';
  14. const TOKEN_LENGHT = 16;
  15. const TYPE_ID_WELCOME = 0;
  16. const TYPE_ID_PREFIX = 1;
  17. const TYPE_ID_CALL = 2;
  18. const TYPE_ID_CALLRESULT = 3;
  19. const TYPE_ID_ERROR = 4;
  20. const TYPE_ID_SUBSCRIBE = 5;
  21. const TYPE_ID_UNSUBSCRIBE = 6;
  22. const TYPE_ID_PUBLISH = 7;
  23. const TYPE_ID_EVENT = 8;
  24. protected $key;
  25. protected $host;
  26. protected $port;
  27. protected $path;
  28. /**
  29. * @var TCP
  30. */
  31. protected $socket;
  32. protected $buffer = '';
  33. /**
  34. * @var bool
  35. */
  36. protected $connected = false;
  37. protected $handshake = false;
  38. protected $ssl = false;
  39. protected $ssl_key_file;
  40. protected $ssl_cert_file;
  41. protected $haveSwooleEncoder = false;
  42. protected $header;
  43. const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  44. const UserAgent = 'SwooleWebsocketClient';
  45. /**
  46. * @param string $host
  47. * @param int $port
  48. * @param string $path
  49. * @throws \Exception
  50. */
  51. function __construct($options, $path = '/')
  52. {
  53. if (empty($options))
  54. {
  55. throw new \Exception("联系webstock服务端配置为空");
  56. }
  57. $this->haveSwooleEncoder = method_exists('swoole_websocket_server', 'pack');
  58. $this->host = $options['host'];
  59. $this->port = $options['port'];
  60. $this->path = $path;
  61. $this->key = $this->generateToken(self::TOKEN_LENGHT);
  62. $this->parser = new WebsocketParser();
  63. var_dump($options);
  64. if($options['ssl'] == true){
  65. self::enableCrypto($options['ssl_key_file'], $options['ssl_cert_file']);
  66. }
  67. if(!self::connect(isset($options['time_out'])?$options['time_out']:0.5)){
  68. throw new \Exception("connect failed. Error:".$this->socket->errCode.PHP_EOL);
  69. }
  70. }
  71. /**
  72. * @param string $keyFile
  73. * @param string $certFile
  74. * @throws Swoole\Http\\Exception
  75. */
  76. function enableCrypto($keyFile = '', $certFile = '')
  77. {
  78. if (!extension_loaded('swoole'))
  79. {
  80. throw new \Exception("require swoole extension.");
  81. }
  82. $this->ssl = true;
  83. $this->ssl_key_file = $keyFile;
  84. $this->ssl_cert_file = $certFile;
  85. }
  86. /**
  87. * Disconnect on destruct
  88. */
  89. function __destruct()
  90. {
  91. if ($this->connected)
  92. {
  93. $this->disconnect();
  94. }
  95. }
  96. /**
  97. * Connect client to server
  98. * @param $timeout
  99. * @return $this
  100. */
  101. public function connect($timeout = 0.5)
  102. {
  103. if (extension_loaded('swoole'))
  104. {
  105. var_dump("xxaa02");
  106. // $type = SWOOLE_TCP;
  107. // if ($this->ssl)
  108. // {
  109. // $type |= SWOOLE_SSL;
  110. // }
  111. // $this->socket = new \swoole_client($type);
  112. if($this->ssl){
  113. $this->socket = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_SSL);
  114. }else{
  115. $this->socket = new \swoole_client(SWOOLE_SOCK_TCP);
  116. }
  117. var_dump("xxaa03");
  118. var_dump($this->ssl_cert_file);
  119. var_dump($this->ssl_key_file);
  120. var_dump($this->ssl);
  121. if ($this->ssl_key_file)
  122. {
  123. var_dump($this->ssl_cert_file);
  124. var_dump("xxaa");
  125. $this->socket->set(array(
  126. 'ssl_key_file' => $this->ssl_key_file,
  127. 'ssl_cert_file' => $this->ssl_cert_file,
  128. /*'open_length_check' => true, // 开启协议解析
  129. 'package_length_type' => 'N', // 长度字段的类型
  130. 'package_length_offset' => 0, //第几个字节是包长度的值
  131. 'package_body_offset' => PACKAGE_BODY_OFFSET, //第几个字节开始计算包内容
  132. 'package_max_length' => PACKAGE_MAXLENG, //协议最大长度*/
  133. ));
  134. }
  135. }
  136. else
  137. {
  138. $this->socket = new \TCP;
  139. var_dump("xxaa01");
  140. }
  141. //建立连接
  142. if (!$this->socket->connect($this->host, $this->port, $timeout))
  143. {
  144. return false;
  145. }
  146. $this->connected = true;
  147. //WebSocket握手
  148. if ($this->socket->send($this->createHeader()) === false)
  149. {
  150. return false;
  151. }
  152. $headerBuffer = '';
  153. while(true)
  154. {
  155. $_tmp = $this->socket->recv();
  156. if ($_tmp)
  157. {
  158. $headerBuffer .= $_tmp;
  159. if (substr($headerBuffer, -4, 4) != "\r\n\r\n")
  160. {
  161. continue;
  162. }
  163. }
  164. else
  165. {
  166. return false;
  167. }
  168. return $this->doHandShake($headerBuffer);
  169. }
  170. return false;
  171. }
  172. /**
  173. * 握手
  174. * @param $headerBuffer
  175. * @return bool
  176. */
  177. function doHandShake($headerBuffer)
  178. {
  179. $header = Parser::parseHeader($headerBuffer);
  180. if (!isset($header['Sec-WebSocket-Accept']))
  181. {
  182. $this->disconnect();
  183. return false;
  184. }
  185. if ($header['Sec-WebSocket-Accept'] != base64_encode(pack('H*', sha1($this->key . self::GUID))))
  186. {
  187. $this->disconnect();
  188. return false;
  189. }
  190. $this->handshake = true;
  191. $this->header = $header;
  192. return true;
  193. }
  194. /**
  195. * Disconnect from server
  196. */
  197. public function disconnect()
  198. {
  199. $this->connected = false;
  200. $this->socket->close();
  201. }
  202. /**
  203. * 接收数据
  204. * @return bool | Swoole\Http\WebSocketFrame
  205. * @throws Swoole\Http\\Exception
  206. */
  207. function recv()
  208. {
  209. if (!$this->handshake)
  210. {
  211. trigger_error("not complete handshake.");
  212. return false;
  213. }
  214. while (true)
  215. {
  216. $data = $this->socket->recv();
  217. if (!$data)
  218. {
  219. return false;
  220. }
  221. $this->parser->push($data);
  222. $frame = $this->parser->pop($data);
  223. if ($frame)
  224. {
  225. return $frame->data;
  226. }
  227. }
  228. return false;
  229. }
  230. /**
  231. * send string data
  232. * @param $data
  233. * @param string $type
  234. * @param bool $masked
  235. * @throws \Exception
  236. * @return bool
  237. */
  238. public function send($data, $type = 'text', $masked = true)
  239. {
  240. if (empty($data))
  241. {
  242. throw new \Exception("data is empty");
  243. }
  244. if (!$this->handshake)
  245. {
  246. trigger_error("not complete handshake.");
  247. return false;
  248. }
  249. if ($this->haveSwooleEncoder)
  250. {
  251. switch($type)
  252. {
  253. case 'text':
  254. $_type = WEBSOCKET_OPCODE_TEXT;
  255. break;
  256. case 'binary':
  257. case 'bin':
  258. $_type = WEBSOCKET_OPCODE_BINARY;
  259. break;
  260. default:
  261. return false;
  262. }
  263. $_send = \swoole_websocket_server::pack($data, $_type);
  264. }
  265. else
  266. {
  267. $_send = $this->hybi10Encode($data, $type, $masked);
  268. }
  269. return $this->socket->send($_send);
  270. }
  271. /**
  272. * send json object
  273. * @param $data
  274. * @param bool $masked
  275. * @return bool
  276. */
  277. function sendJson($data, $masked = true)
  278. {
  279. return $this->send(json_encode($data, JSON_UNESCAPED_UNICODE).PACKAGE_EOF, 'text', $masked);
  280. }
  281. /**
  282. * Create header for websocket client
  283. * @return string
  284. */
  285. final protected function createHeader()
  286. {
  287. $host = $this->host;
  288. if ($host === '127.0.0.1' || $host === '0.0.0.0')
  289. {
  290. $host = 'localhost';
  291. }
  292. return "GET {$this->path} HTTP/1.1" . "\r\n" .
  293. "Origin: null" . "\r\n" .
  294. "Host: {$host}:{$this->port}" . "\r\n" .
  295. "Sec-WebSocket-Key: {$this->key}" . "\r\n" .
  296. "User-Agent: ".self::UserAgent."/" . self::VERSION . "\r\n" .
  297. "Upgrade: Websocket" . "\r\n" .
  298. "Connection: Upgrade" . "\r\n" .
  299. "Sec-WebSocket-Protocol: wamp" . "\r\n" .
  300. "Sec-WebSocket-Version: 13" . "\r\n" . "\r\n";
  301. }
  302. /**
  303. * Parse raw incoming data
  304. *
  305. * @param $header
  306. * @return array
  307. */
  308. final protected function parseIncomingRaw($header)
  309. {
  310. $retval = array();
  311. $content = "";
  312. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
  313. foreach ($fields as $field) {
  314. if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
  315. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function ($matches) {
  316. return strtoupper($matches[0]);
  317. }, strtolower(trim($match[1])));
  318. if (isset($retval[$match[1]])) {
  319. $retval[$match[1]] = array($retval[$match[1]], $match[2]);
  320. } else {
  321. $retval[$match[1]] = trim($match[2]);
  322. }
  323. } else if (preg_match('!HTTP/1\.\d (\d)* .!', $field)) {
  324. $retval["status"] = $field;
  325. } else {
  326. $content .= $field . "\r\n";
  327. }
  328. }
  329. $retval['content'] = $content;
  330. return $retval;
  331. }
  332. /**
  333. * Generate token
  334. *
  335. * @param int $length
  336. * @return string
  337. */
  338. private function generateToken($length)
  339. {
  340. $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
  341. $useChars = array();
  342. // select some random chars:
  343. for ($i = 0; $i < $length; $i++) {
  344. $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
  345. }
  346. // Add numbers
  347. array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
  348. shuffle($useChars);
  349. $randomString = trim(implode('', $useChars));
  350. $randomString = substr($randomString, 0, self::TOKEN_LENGHT);
  351. return base64_encode($randomString);
  352. }
  353. /**
  354. * Generate token
  355. *
  356. * @param int $length
  357. * @return string
  358. */
  359. public function generateAlphaNumToken($length)
  360. {
  361. $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
  362. srand((float)microtime() * 1000000);
  363. $token = '';
  364. do
  365. {
  366. shuffle($characters);
  367. $token .= $characters[mt_rand(0, (count($characters) - 1))];
  368. } while (strlen($token) < $length);
  369. return $token;
  370. }
  371. /**
  372. * @param $payload
  373. * @param string $type
  374. * @param bool $masked
  375. * @return bool|string
  376. */
  377. private function hybi10Encode($payload, $type = 'text', $masked = true)
  378. {
  379. $frameHead = array();
  380. $payloadLength = strlen($payload);
  381. switch ($type)
  382. {
  383. //文本内容
  384. case 'text':
  385. // first byte indicates FIN, Text-Frame (10000001):
  386. $frameHead[0] = 129;
  387. break;
  388. //二进制内容
  389. case 'binary':
  390. case 'bin':
  391. // first byte indicates FIN, Text-Frame (10000010):
  392. $frameHead[0] = 130;
  393. break;
  394. case 'close':
  395. // first byte indicates FIN, Close Frame(10001000):
  396. $frameHead[0] = 136;
  397. break;
  398. case 'ping':
  399. // first byte indicates FIN, Ping frame (10001001):
  400. $frameHead[0] = 137;
  401. break;
  402. case 'pong':
  403. // first byte indicates FIN, Pong frame (10001010):
  404. $frameHead[0] = 138;
  405. break;
  406. }
  407. // set mask and payload length (using 1, 3 or 9 bytes)
  408. if ($payloadLength > 65535)
  409. {
  410. $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
  411. $frameHead[1] = ($masked === true) ? 255 : 127;
  412. for ($i = 0; $i < 8; $i++)
  413. {
  414. $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
  415. }
  416. // most significant bit MUST be 0 (close connection if frame too big)
  417. if ($frameHead[2] > 127)
  418. {
  419. $this->socket->close();
  420. return false;
  421. }
  422. }
  423. elseif ($payloadLength > 125)
  424. {
  425. $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
  426. $frameHead[1] = ($masked === true) ? 254 : 126;
  427. $frameHead[2] = bindec($payloadLengthBin[0]);
  428. $frameHead[3] = bindec($payloadLengthBin[1]);
  429. }
  430. else
  431. {
  432. $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
  433. }
  434. // convert frame-head to string:
  435. foreach (array_keys($frameHead) as $i)
  436. {
  437. $frameHead[$i] = chr($frameHead[$i]);
  438. }
  439. // generate a random mask:
  440. $mask = array();
  441. if ($masked === true)
  442. {
  443. for ($i = 0; $i < 4; $i++)
  444. {
  445. $mask[$i] = chr(rand(0, 255));
  446. }
  447. $frameHead = array_merge($frameHead, $mask);
  448. }
  449. $frame = implode('', $frameHead);
  450. // append payload to frame:
  451. for ($i = 0; $i < $payloadLength; $i++)
  452. {
  453. $frame .= $masked ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
  454. }
  455. return $frame;
  456. }
  457. /**
  458. * @param $data
  459. * @return string
  460. * @throws \Exception
  461. */
  462. private function hybi10Decode($data)
  463. {
  464. if (empty($data))
  465. {
  466. throw new \Exception("data is empty");
  467. }
  468. $bytes = $data;
  469. $secondByte = sprintf('%08b', ord($bytes[1]));
  470. $masked = ($secondByte[0] == '1') ? true : false;
  471. $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
  472. //服务器不会设置mask
  473. if ($dataLength === 126)
  474. {
  475. $decodedData = substr($bytes, 4);
  476. }
  477. elseif ($dataLength === 127)
  478. {
  479. $decodedData = substr($bytes, 10);
  480. }
  481. else
  482. {
  483. $decodedData = substr($bytes, 2);
  484. }
  485. exit("len=".$dataLength."\n");
  486. return $decodedData;
  487. }
  488. }