search
HomeBackend DevelopmentPHP Tutorialphp+html5 method to implement chat room based on websocket

The example in this article describes the method of implementing a chat room based on websocket using php+html5. Share it with everyone for your reference. The details are as follows:

html5’s websocket realizes two-way communication. After a few days of hard work, I made a chat room and share it with everyone

<?php
error_reporting(E_ALL);
ob_implicit_flush();
$sk=new Sock(&#39;127.0.0.1&#39;,8000);
$sk->run();
class Sock{
 public $sockets;
 public $users;
 public $master;
 public function __construct($address, $port){
  $this->master=$this->WebSocket($address, $port);
  $this->sockets=array(&#39;s&#39;=>$this->master);
 }
 function run(){
  while(true){
   $changes=$this->sockets;
   socket_select($changes,$write=NULL,$except=NULL,NULL);
   foreach($changes as $sock){
    if($sock==$this->master){
     $client=socket_accept($this->master);
     //$key=uniqid();
     $this->sockets[]=$client;
     $this->users[]=array(
      &#39;socket&#39;=>$client,
      &#39;shou&#39;=>false
     );
    }else{
     $len=socket_recv($sock,$buffer,2048,0);
     $k=$this->search($sock);
     if($len<7){
      $name=$this->users[$k][&#39;ming&#39;];
      $this->close($sock);
      $this->send2($name,$k);
      continue;
     }
     if(!$this->users[$k][&#39;shou&#39;]){
      $this->woshou($k,$buffer);
     }else{
      $buffer = $this->uncode($buffer);
      $this->send($k,$buffer);
     }
    }
   }
  }
 }
 function close($sock){
  $k=array_search($sock, $this->sockets);
  socket_close($sock);
  unset($this->sockets[$k]);
  unset($this->users[$k]);
  $this->e("key:$k close");
 }
 function search($sock){
  foreach ($this->users as $k=>$v){
   if($sock==$v[&#39;socket&#39;])
   return $k;
  }
  return false;
 }
 function WebSocket($address,$port){
  $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
  socket_bind($server, $address, $port);
  socket_listen($server);
  $this->e(&#39;Server Started : &#39;.date(&#39;Y-m-d H:i:s&#39;));
  $this->e(&#39;Listening on : &#39;.$address.&#39; port &#39;.$port);
  return $server;
 }
 function woshou($k,$buffer){
  $buf = substr($buffer,strpos($buffer,&#39;Sec-WebSocket-Key:&#39;)+18);
  $key = trim(substr($buf,0,strpos($buf,"\r\n")));
  $new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  $new_message .= "Upgrade: websocket\r\n";
  $new_message .= "Sec-WebSocket-Version: 13\r\n";
  $new_message .= "Connection: Upgrade\r\n";
  $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  socket_write($this->users[$k][&#39;socket&#39;],$new_message,strlen($new_message));
  $this->users[$k][&#39;shou&#39;]=true;
  return true;
 }
 function uncode($str){
  $mask = array(); 
  $data = &#39;&#39;; 
  $msg = unpack(&#39;H*&#39;,$str); 
  $head = substr($msg[1],0,2); 
  if (hexdec($head{1}) === 8) { 
   $data = false; 
  }else if (hexdec($head{1}) === 1){ 
   $mask[] = hexdec(substr($msg[1],4,2)); 
   $mask[] = hexdec(substr($msg[1],6,2)); 
   $mask[] = hexdec(substr($msg[1],8,2)); 
   $mask[] = hexdec(substr($msg[1],10,2)); 
   $s = 12; 
   $e = strlen($msg[1])-2; 
   $n = 0; 
   for ($i=$s; $i<= $e; $i+= 2) { 
    $data .= chr($mask[$n%4]^hexdec(substr($msg[1],$i,2)));
    $n++; 
   } 
  } 
  return $data;
 }
 function code($msg){
  $msg = preg_replace(array(&#39;/\r$/&#39;,&#39;/\n$/&#39;,&#39;/\r\n$/&#39;,), &#39;&#39;, $msg);
  $frame = array(); 
  $frame[0] = &#39;81&#39;; 
  $len = strlen($msg); 
  $frame[1] = $len<16?&#39;0&#39;.dechex($len):dechex($len); 
  $frame[2] = $this->ord_hex($msg); 
  $data = implode(&#39;&#39;,$frame); 
  return pack("H*", $data); 
 }
 function ord_hex($data) { 
  $msg = &#39;&#39;; 
  $l = strlen($data); 
  for ($i= 0; $i<$l; $i++) { 
   $msg .= dechex(ord($data{$i})); 
  } 
  return $msg; 
 }
 function send($k,$msg){
  /*$this->send1($k,$this->code($msg),&#39;all&#39;);*/
  parse_str($msg,$g);
  $this->e($msg);
  $ar=array();
  if($g[&#39;type&#39;]==&#39;add&#39;){
   $this->users[$k][&#39;ming&#39;]=$g[&#39;ming&#39;];
   $ar[&#39;add&#39;]=true;
   $ar[&#39;nrong&#39;]=&#39;欢迎&#39;.$g[&#39;ming&#39;].&#39;加入!&#39;;
   $ar[&#39;users&#39;]=$this->getusers();
   $key=&#39;all&#39;;
  }else if($g[&#39;type&#39;]==&#39;ltiao&#39;){
   $ar[&#39;nrong&#39;]=$g[&#39;nr&#39;];
   $key=$g[&#39;key&#39;];
  }
  $msg=json_encode($ar);
  $this->e($msg);
  $msg = $this->code($msg);
  $this->send1($k,$msg,$key);
  //socket_write($this->users[$k][&#39;socket&#39;],$msg,strlen($msg));
 }
 function getusers(){
  $ar=array();
  foreach($this->users as $k=>$v){
   $ar[$k]=$v[&#39;ming&#39;];
  }
  return $ar;
 }
 function send1($k,$str,$key=&#39;all&#39;){
  if($key==&#39;all&#39;){
   foreach($this->users as $v){
    socket_write($v[&#39;socket&#39;],$str,strlen($str));
   }
  }else{
   if($k!=$key)
   socket_write($this->users[$k][&#39;socket&#39;],$str,strlen($str));
   socket_write($this->users[$key][&#39;socket&#39;],$str,strlen($str));
  }
 }
 function send2($ming,$k){
  $ar[&#39;remove&#39;]=true;
  $ar[&#39;removekey&#39;]=$k;
  $ar[&#39;nrong&#39;]=$ming.&#39;退出聊天室&#39;;
  $str = $this->code(json_encode($ar));
  $this->send1(false,$str,&#39;all&#39;);
 }
 function e($str){
  $path=dirname(__FILE__).&#39;/log.txt&#39;;
  $str=$str."\n";
  error_log($str,3,$path);
  echo iconv(&#39;utf-8&#39;,&#39;gbk//IGNORE&#39;,$str);
 }
}
?>

The above is the content of php+html5’s method of implementing a chat room based on websocket, and more related content Please pay attention to the PHP Chinese website (www.php.cn)!

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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

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

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)