WebsocketClient.Class.php 14 KB

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