国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Create WebSocket service using php

Create WebSocket service using php

Jul 25, 2016 am 08:50 AM

Execution method:
First modify the ip of server.php and index.html
Execute through the command line [php path]php.exe "[file path]server.php"
Then open index.html through the browser
  1. include 'websocket.class.php';
  2. $config=array(
  3. 'address'=>'192.168.0.200',
  4. 'port'=>'8000',
  5. ' event'=>'WSevent',//The function name of the callback function
  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('Customer entry id:'.$event['k']) ;
  14. }elseif('out'==$type){
  15. $websocket->log('Customer exit id:'.$event['k']);
  16. }elseif('msg'==$type) {
  17. $websocket->log($event['k'].'Message:'.$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='Current time:'.date('Y-m-d H:i:s');
  33. break;
  34. case 'Goodbye':
  35. $show='( ^_^ )/~~Bye';
  36. $websocket->write($sign,'Robot:'.$show);
  37. $websocket->close($ sign);
  38. return;
  39. break;
  40. case 'Heavenly King Covers Earthly Tiger':
  41. $array = array('Chicken stewed with mushrooms', 'Pagoda shakes the river demon', 'Every grain of it is hard work');
  42. $show = $array[rand(0,2)];
  43. break;
  44. default:
  45. $show='( ⊙o⊙?) If you don’t understand, you can try saying: hello, name, time, goodbye, the king of heaven covers the earth and the tiger.' ;
  46. }
  47. $websocket->write($sign,'Robot:'.$show);
  48. }
  49. ?>
Copy code
  1. websocket_TEST
  2. <script></li> <li>function link(){</li> <li> var url='ws: //192.168.0.200:8000';</li> <li> socket=new WebSocket(url);</li> <li> socket.onopen=function(){log('Connection successful')}</li> <li> socket.onmessage=function(msg){log('Get message :'+msg.data);console.log(msg);}</li> <li> socket.onclose=function(){log('disconnect')}</li> <li>}</li> <li>function dis(){</li> <li> socket.close();</li> <li> socket=null;</li> <li>}</li> <li>function log(var1){</li> <li> $('.log').append(var1+"rn");</li> <li>}</li> <li>function send(){</li> <li> socket.send($('#text') .attr('value'));</li> <li>}</li> <li>function send2(){</li> <li> var json = JSON.stringify({'type':'php','msg':$('#text2').attr('value ')})</li> <li> socket.send(json);</li> <li>}</li> <li></script>
Copy code
  1. /*
  2. Create class websocket($config);
  3. $config structure:
  4. $config=array(
  5. 'address'=>'192.168.0.200',//Bind address
  6. 'port'=>'8000',//Bind port
  7. 'event'=>'WSevent',//The function name of the callback function
  8. 'log'=>true,//The command line displays records
  9. ) ;
  10. Callback function return data format
  11. function WSevent($type,$event)
  12. $type string event types have the following three types
  13. in client enters
  14. out client disconnects
  15. msg client message arrives
  16. all are Lower case
  17. $event array
  18. $event['k'] userid of built-in user list;
  19. $event['sign'] customer mark
  20. $event['msg'] only when message $type='msg' is received There is this information
  21. Method:
  22. run() run
  23. search(label) traverse to get the id of the label
  24. close(label) disconnect
  25. write(label, information) push information
  26. idwrite(id, information) push information
  27. Attribute:
  28. $users customer list
  29. Structure:
  30. $users=array(
  31. [user id]=>array('socket'=>[mark],'hand'=[whether to shake hands - Boolean value]),
  32. [userid]=>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("Please run through command line mode!");
  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('Start listening: '.$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']){//No handshake for handshake
  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){//Get the id through sign traversal
  99. foreach ($this->users as $k= >$v){
  100. if($sign==$v['socket'])
  101. return $k;
  102. }
  103. return false;
  104. }
  105. function close($sign){//Disconnect via 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,"rn")));
  114. $new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  115. $new_message = " HTTP/1.1 101 Switching Protocolsrn";
  116. $new_message .= "Upgrade: websocketrn";
  117. $new_message .= "Sec-WebSocket-Version: 13rn";
  118. $new_message .= "Connection: Upgradern";
  119. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "rnrn";
  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$/','/rn$/',), '', $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;}//沒有這個(gè)標(biāo)示
  166. $t=$this->code($t);
  167. return socket_write($this->users[$id]['socket'],$t,strlen($t));
  168. }
  169. function write($k,$t){//通過標(biāo)示推送信息
  170. $t=$this->code($t);
  171. return socket_write($k,$t,strlen($t));
  172. }
  173. function eventoutput($type,$event){//事件回調(diào)
  174. call_user_func($this->event,$type,$event);
  175. }
  176. function log($t){//控制臺輸出
  177. if($this->log){
  178. $t=$t."rn";
  179. fwrite(STDOUT, iconv('utf-8','gbk//IGNORE',$t));
  180. }
  181. }
  182. }
復(fù)制代碼


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

See all articles