使用php创建WebSocket服务

发表于2017-08-01
评论0 2.2k浏览
本篇文章给大家介绍如何使用php创建WebSocket服务,如果对使用php创建WebSocket服务的可以看一看,或许能帮到你们。

执行方法:
首先先修改server.php与index.html的ip
通过命令行执行 [php路径]\php.exe "[文件路径]\server.php"
然后通过浏览器打开index.html
  1. include 'websocket.class.php';
  2. $config=array(
  3. 'address'=>'192.168.0.200',
  4. 'port'=>'8000',
  5. 'event'=>'WSevent',//回调函数的函数名
  6. 'log'=>true,
  7. );
  8. $websocket = new websocket($config);
  9. $websocket->run();
  10. function WSevent($type,$event){
  11. global $websocket;
  12. if('in'==$type){
  13. $websocket->log('客户进入id:'.$event['k']);
  14. }elseif('out'==$type){
  15. $websocket->log('客户退出id:'.$event['k']);
  16. }elseif('msg'==$type){
  17. $websocket->log($event['k'].'消息:'.$event['msg']);
  18. roboot($event['sign'],$event['msg']);
  19. }
  20. }
  21. function roboot($sign,$t){
  22. global $websocket;
  23. switch ($t)
  24. {
  25. case 'hello':
  26. $show='hello,GIt @ OSC';
  27. break;
  28. case 'name':
  29. $show='Robot';
  30. break;
  31. case 'time':
  32. $show='当前时间:'.date('Y-m-d H:i:s');
  33. break;
  34. case '再见':
  35. $show='( ^_^ )/~~拜拜';
  36. $websocket->write($sign,'Robot:'.$show);
  37. $websocket->close($sign);
  38. return;
  39. break;
  40. case '天王盖地虎':
  41. $array = array('小鸡炖蘑菇','宝塔震河妖','粒粒皆辛苦');
  42. $show = $array[rand(0,2)];
  43. break;
  44. default:
  45. $show='( ⊙o⊙?)不懂,你可以尝试说:hello,name,time,再见,天王盖地虎.';
  46. }
  47. $websocket->write($sign,'Robot:'.$show);
  48. }
  49. ?>
复制代码
复制代码
  1. /*
  2. 创建类websocket($config);
  3. $config结构:
  4. $config=array(
  5. 'address'=>'192.168.0.200',//绑定地址
  6. 'port'=>'8000',//绑定端口
  7. 'event'=>'WSevent',//回调函数的函数名
  8. 'log'=>true,//命令行显示记录
  9. );
  10. 回调函数返回数据格式
  11. function WSevent($type,$event)
  12. $type字符串 事件类型有以下三种
  13. in 客户端进入
  14. out 客户端断开
  15. msg 客户端消息到达
  16. 均为小写
  17. $event 数组
  18. $event['k']内置用户列表的userid;
  19. $event['sign']客户标示
  20. $event['msg']收到的消息 $type='msg'时才有该信息
  21. 方法:
  22. run()运行
  23. search(标示)遍历取得该标示的id
  24. close(标示)断开连接
  25. write(标示,信息)推送信息
  26. idwrite(id,信息)推送信息
  27. 属性:
  28. $users 客户列表
  29. 结构:
  30. $users=array(
  31. [用户id]=>array('socket'=>[标示],'hand'=[是否握手-布尔值]),
  32. [用户id]=>arr.....
  33. )
  34. */
  35. class websocket{
  36. public $log;
  37. public $event;
  38. public $signets;
  39. public $users;
  40. public $master;
  41. public function __construct($config){
  42. if (substr(php_sapi_name(), 0, 3) !== 'cli') {
  43. die("请通过命令行模式运行!");
  44. }
  45. error_reporting(E_ALL);
  46. set_time_limit(0);
  47. ob_implicit_flush();
  48. $this->event = $config['event'];
  49. $this->log = $config['log'];
  50. $this->master=$this->WebSocket($config['address'], $config['port']);
  51. $this->sockets=array('s'=>$this->master);
  52. }
  53. function WebSocket($address,$port){
  54. $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  55. socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
  56. socket_bind($server, $address, $port);
  57. socket_listen($server);
  58. $this->log('开始监听: '.$address.' : '.$port);
  59. return $server;
  60. }
  61. function run(){
  62. while(true){
  63. $changes=$this->sockets;
  64. @socket_select($changes,$write=NULL,$except=NULL,NULL);
  65. foreach($changes as $sign){
  66. if($sign==$this->master){
  67. $client=socket_accept($this->master);
  68. $this->sockets[]=$client;
  69. $user = array(
  70. 'socket'=>$client,
  71. 'hand'=>false,
  72. );
  73. $this->users[] = $user;
  74. $k=$this->search($client);
  75. $eventreturn = array('k'=>$k,'sign'=>$sign);
  76. $this->eventoutput('in',$eventreturn);
  77. }else{
  78. $len=socket_recv($sign,$buffer,2048,0);
  79. $k=$this->search($sign);
  80. $user=$this->users[$k];
  81. if($len<7){
  82. $this->close($sign);
  83. $eventreturn = array('k'=>$k,'sign'=>$sign);
  84. $this->eventoutput('out',$eventreturn);
  85. continue;
  86. }
  87. if(!$this->users[$k]['hand']){//没有握手进行握手
  88. $this->handshake($k,$buffer);
  89. }else{
  90. $buffer = $this->uncode($buffer);
  91. $eventreturn = array('k'=>$k,'sign'=>$sign,'msg'=>$buffer);
  92. $this->eventoutput('msg',$eventreturn);
  93. }
  94. }
  95. }
  96. }
  97. }
  98. function search($sign){//通过标示遍历获取id
  99. foreach ($this->users as $k=>$v){
  100. if($sign==$v['socket'])
  101. return $k;
  102. }
  103. return false;
  104. }
  105. function close($sign){//通过标示断开连接
  106. $k=array_search($sign, $this->sockets);
  107. socket_close($sign);
  108. unset($this->sockets[$k]);
  109. unset($this->users[$k]);
  110. }
  111. function handshake($k,$buffer){
  112. $buf = substr($buffer,strpos($buffer,'Sec-WebSocket-Key:') 18);
  113. $key = trim(substr($buf,0,strpos($buf,"\r\n")));
  114. $new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  115. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  116. $new_message .= "Upgrade: websocket\r\n";
  117. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  118. $new_message .= "Connection: Upgrade\r\n";
  119. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  120. socket_write($this->users[$k]['socket'],$new_message,strlen($new_message));
  121. $this->users[$k]['hand']=true;
  122. return true;
  123. }
  124. function uncode($str){
  125. $mask = array();
  126. $data = '';
  127. $msg = unpack('H*',$str);
  128. $head = substr($msg[1],0,2);
  129. if (hexdec($head小贝) === 8) {
  130. $data = false;
  131. }else if (hexdec($head小贝) === 1){
  132. $mask[] = hexdec(substr($msg[1],4,2));
  133. $mask[] = hexdec(substr($msg[1],6,2));
  134. $mask[] = hexdec(substr($msg[1],8,2));
  135. $mask[] = hexdec(substr($msg[1],10,2));
  136. $s = 12;
  137. $e = strlen($msg[1])-2;
  138. $n = 0;
  139. for ($i=$s; $i<= $e; $i = 2) {
  140. $data .= chr($mask[$n%4]^hexdec(substr($msg[1],$i,2)));
  141. $n ;
  142. }
  143. }
  144. return $data;
  145. }
  146. function code($msg){
  147. $msg = preg_replace(array('/\r$/','/\n$/','/\r\n$/',), '', $msg);
  148. $frame = array();
  149. $frame[0] = '81';
  150. $len = strlen($msg);
  151. $frame[1] = $len<16?'0'.dechex($len):dechex($len);
  152. $frame[2] = $this->ord_hex($msg);
  153. $data = implode('',$frame);
  154. return pack("H*", $data);
  155. }
  156. function ord_hex($data) {
  157. $msg = '';
  158. $l = strlen($data);
  159. for ($i= 0; $i<$l; $i ) {
  160. $msg .= dechex(ord($data{$i}));
  161. }
  162. return $msg;
  163. }
  164. function idwrite($id,$t){//通过id推送信息
  165. if(!$this->users[$id]['socket']){return false;}//没有这个标示
  166. $t=$this->code($t);
  167. return socket_write($this->users[$id]['socket'],$t,strlen($t));
  168. }
  169. function write($k,$t){//通过标示推送信息
  170. $t=$this->code($t);
  171. return socket_write($k,$t,strlen($t));
  172. }
  173. function eventoutput($type,$event){//事件回调
  174. call_user_func($this->event,$type,$event);
  175. }
  176. function log($t){//控制台输出
  177. if($this->log){
  178. $t=$t."\r\n";
  179. fwrite(STDOUT, iconv('utf-8','gbk//IGNORE',$t));
  180. }
  181. }
  182. }

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引