socketservice.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. <?php
  2. /**
  3. * Created by xwx
  4. * Date: 2017/10/18
  5. * Time: 14:33
  6. */
  7. class SocketService
  8. {
  9. private $address = '0.0.0.0';
  10. private $port = 8083;
  11. private $_sockets;
  12. public function __construct($address = '', $port = '')
  13. {
  14. if (!empty($address)) {
  15. $this->address = $address;
  16. }
  17. if (!empty($port)) {
  18. $this->port = $port;
  19. }
  20. }
  21. public function service()
  22. {
  23. //获取tcp协议号码。
  24. $tcp = getprotobyname("tcp");
  25. $sock = socket_create(AF_INET, SOCK_STREAM, $tcp);
  26. socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
  27. if ($sock < 0) {
  28. throw new Exception("failed to create socket: " . socket_strerror($sock) . "\n");
  29. }
  30. socket_bind($sock, $this->address, $this->port);
  31. socket_listen($sock, $this->port);
  32. echo "listen on $this->address $this->port ... \n";
  33. $this->_sockets = $sock;
  34. }
  35. public function run()
  36. {
  37. $this->service();
  38. $clients[] = $this->_sockets;
  39. while (true) {
  40. $changes = $clients;
  41. $write = NULL;
  42. $except = NULL;
  43. socket_select($changes, $write, $except, NULL);
  44. foreach ($changes as $key => $_sock) {
  45. if ($this->_sockets == $_sock) { //判断是不是新接入的socket
  46. if (($newClient = socket_accept($_sock)) === false) {
  47. die('failed to accept socket: ' . socket_strerror($_sock) . "\n");
  48. }
  49. $line = trim(socket_read($newClient, 1024));
  50. $this->handshaking($newClient, $line);
  51. //获取client ip
  52. socket_getpeername($newClient, $ip);
  53. $clients[$ip] = $newClient;
  54. echo "Client ip:{$ip} \n";
  55. echo "Client msg:{$line} \n";
  56. } else {
  57. socket_recv($_sock, $buffer, 2048, 0);
  58. $msg = $this->message($buffer);
  59. //在这里业务代码
  60. echo "{$key} clinet msg:", $msg, "\n";
  61. fwrite(STDOUT, 'Please input a argument:');
  62. $response = trim(fgets(STDIN));
  63. $this->send($_sock, $response);
  64. echo "{$key} response to Client:" . $response, "\n";
  65. }
  66. }
  67. }
  68. }
  69. /**
  70. * 握手处理
  71. * @param $newClient socket
  72. * @return int 接收到的信息
  73. */
  74. public function handshaking($newClient, $line)
  75. {
  76. $headers = array();
  77. $lines = preg_split("/\r\n/", $line);
  78. foreach ($lines as $line) {
  79. $line = chop($line);
  80. if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
  81. $headers[$matches[1]] = $matches[2];
  82. }
  83. }
  84. $secKey = $headers['Sec-WebSocket-Key'];
  85. $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
  86. $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
  87. "Upgrade: websocket\r\n" .
  88. "Connection: Upgrade\r\n" .
  89. "WebSocket-Origin: $this->address\r\n" .
  90. "WebSocket-Location: ws://$this->address:$this->port/websocket/websocket\r\n" .
  91. "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
  92. return socket_write($newClient, $upgrade, strlen($upgrade));
  93. }
  94. /**
  95. * 解析接收数据
  96. * @param $buffer
  97. * @return null|string
  98. */
  99. public function message($buffer)
  100. {
  101. $len = $masks = $data = $decoded = null;
  102. $len = ord($buffer[1]) & 127;
  103. if ($len === 126) {
  104. $masks = substr($buffer, 4, 4);
  105. $data = substr($buffer, 8);
  106. } else if ($len === 127) {
  107. $masks = substr($buffer, 10, 4);
  108. $data = substr($buffer, 14);
  109. } else {
  110. $masks = substr($buffer, 2, 4);
  111. $data = substr($buffer, 6);
  112. }
  113. for ($index = 0; $index < strlen($data); $index++) {
  114. $decoded .= $data[$index] ^ $masks[$index % 4];
  115. }
  116. return $decoded;
  117. }
  118. /**
  119. * 发送数据
  120. * @param $newClinet 新接入的socket
  121. * @param $msg 要发送的数据
  122. * @return int|string
  123. */
  124. public function send($newClinet, $msg)
  125. {
  126. $msg = $this->frame($msg);
  127. socket_write($newClinet, $msg, strlen($msg));
  128. }
  129. public function frame($s)
  130. {
  131. $a = str_split($s, 125);
  132. if (count($a) == 1) {
  133. return "\x81" . chr(strlen($a[0])) . $a[0];
  134. }
  135. $ns = "";
  136. foreach ($a as $o) {
  137. $ns .= "\x81" . chr(strlen($o)) . $o;
  138. }
  139. return $ns;
  140. }
  141. /**
  142. * 关闭socket
  143. */
  144. public function close()
  145. {
  146. return socket_close($this->_sockets);
  147. }
  148. }
  149. $sock = new SocketService('0.0.0.0', '9003');
  150. $sock->run();