search
HomeBackend DevelopmentPHP TutorialCreate WebSocket service using php

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>function link(){<li> var url='ws: //192.168.0.200:8000';<li> socket=new WebSocket(url);<li> socket.onopen=function(){log('Connection successful')}<li> socket.onmessage=function(msg){log('Get message :'+msg.data);console.log(msg);}<li> socket.onclose=function(){log('disconnect')}<li>}<li>function dis(){<li> socket.close();<li> socket=null;<li>}<li>function log(var1){<li> $('.log').append(var1+"rn");<li>}<li>function send(){<li> socket.send($('#text') .attr('value'));<li>}<li>function send2(){<li> var json = JSON.stringify({'type':'php','msg':$('#text2').attr('value ')})<li> socket.send(json);<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 $this->close ($sign);
  82. $eventreturn = array('k'=>$k,'sign'=>$sign);
  83. $this->eventoutput('out',$eventreturn);
  84. continue;
  85. }
  86. if(!$this->users[$k]['hand']){//No handshake for handshake
  87. $this->handshake($k,$buffer);
  88. }else{
  89. $buffer = $this->uncode($buffer);
  90. $eventreturn = array('k'=>$k,'sign'=>$sign,'msg'=>$buffer);
  91. $this- >eventoutput('msg',$eventreturn);
  92. }
  93. }
  94. }
  95. }
  96. }
  97. function search($sign){//Get the id through sign traversal
  98. foreach ($this->users as $k= >$v){
  99. if($sign==$v['socket'])
  100. return $k;
  101. }
  102. return false;
  103. }
  104. function close($sign){//Disconnect via sign
  105. $k=array_search($sign, $this->sockets);
  106. socket_close($sign);
  107. unset($this->sockets[$k]);
  108. unset($this->users[$k ]);
  109. }
  110. function handshake($k,$buffer){
  111. $buf = substr($buffer,strpos($buffer,'Sec-WebSocket-Key:')+18);
  112. $key = trim(substr ($buf,0,strpos($buf,"rn")));
  113. $new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  114. $new_message = " HTTP/1.1 101 Switching Protocolsrn";
  115. $new_message .= "Upgrade: websocketrn";
  116. $new_message .= "Sec-WebSocket-Version: 13rn";
  117. $new_message .= "Connection: Upgradern";
  118. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "rnrn";
  119. socket_write($this->users[$k]['socket'],$new_message,strlen($new_message));
  120. $this-> ;users[$k]['hand']=true;
  121. return true;
  122. }
  123. function uncode($str){
  124. $mask = array();
  125. $data = '';
  126. $msg = unpack('H*',$str);
  127. $head = substr($msg[1],0,2);
  128. if (hexdec($head小贝) === 8) {
  129. $data = false;
  130. }else if (hexdec($head小贝) === 1){
  131. $mask[] = hexdec(substr($msg[1],4,2));
  132. $mask[] = hexdec(substr($msg[1],6,2));
  133. $mask[] = hexdec(substr($msg[1],8,2));
  134. $mask[] = hexdec(substr($msg[1],10,2));
  135. $s = 12;
  136. $e = strlen($msg[1])-2;
  137. $n = 0;
  138. for ($i=$s; $i $data .= chr($mask[$n%4]^hexdec(substr($msg[1],$i,2)));
  139. $n++;
  140. }
  141. }
  142. return $data;
  143. }
  144. function code($msg){
  145. $msg = preg_replace(array('/r$/','/n$/','/rn$/',), '', $msg);
  146. $frame = array();
  147. $frame[0] = '81';
  148. $len = strlen($msg);
  149. $frame[1] = $len $frame[2] = $this->ord_hex($msg);
  150. $data = implode('',$frame);
  151. return pack("H*", $data);
  152. }
  153. function ord_hex($data) {
  154. $msg = '';
  155. $l = strlen($data);
  156. for ($i= 0; $i $msg .= dechex(ord($data{$i}));
  157. }
  158. return $msg;
  159. }
  160. function idwrite($id,$t){//通过id推送信息
  161. if(!$this->users[$id]['socket']){return false;}//没有这个标示
  162. $t=$this->code($t);
  163. return socket_write($this->users[$id]['socket'],$t,strlen($t));
  164. }
  165. function write($k,$t){//通过标示推送信息
  166. $t=$this->code($t);
  167. return socket_write($k,$t,strlen($t));
  168. }
  169. function eventoutput($type,$event){//事件回调
  170. call_user_func($this->event,$type,$event);
  171. }
  172. function log($t){//控制台输出
  173. if($this->log){
  174. $t=$t."rn";
  175. fwrite(STDOUT, iconv('utf-8','gbk//IGNORE',$t));
  176. }
  177. }
  178. }
复制代码


Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use