WebsocketClient.Class.php 14 KB

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