Php+html5 method of realizing chat room based on WebSocket _php skill

Source: Internet
Author: User
Tags ming php programming strlen

This article illustrates the PHP+HTML5 method based on WebSocket to realize the chat room. Share to everyone for your reference. as follows:

HTML5 WebSocket realize two-way communication, toss a few days to get a chat room, share to everyone

<?php error_reporting (E_all);
Ob_implicit_flush ();
$sk =new sock (' 127.0.0.1 ', 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 (' s ' => $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 (' socket ' => $client, ' Shou ' =>false);
     }else{$len =socket_recv ($sock, $buffer, 2048,0);
     $k = $this->search ($sock);
      if ($len <7) {$name = $this->users[$k] [' Ming '];
      $this->close ($sock);
      $this->send2 ($name, $k);
     Continue } if (! $this->users[$k] [' Shou ']) {$this->woshou ($K, $buffer);
      }else{$buffer = $this->uncode ($buffer);
     $this->send ($k, $buffer);
  The 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 [' socket ']) 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 (' Server started: '. Date (' y-m-d h:i:s '));
  $this->e (' listening on: '. $address. ' Port ' $port);
 return $server;
  function Woshou ($k, $buffer) {$buf = substr ($buffer, Strpos ($buffer, ' Sec-websocket-key: ') +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 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] [' socket '], $new _message,strlen ($new _message));
  $this->users[$k] [' Shou ']=true;
 return true; 
  function Uncode ($str) {$mask = array (); 
  $data = '; 
  $msg = Unpack (' h* ', $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
  The function code ($msg) {$msg = preg_replace (Array ('/\r$/', '/\n$/', '/\r\n$/',), ', $msg); 
  $frame = Array (); 
  $frame [0] = ' 81 '; 
  $len = strlen ($msg); $frame [1] = $len <16? ' 
  0 '. Dechex ($len):d Echex ($len); 
  $frame [2] = $this->ord_hex ($msg); 
  $data = Implode (", $frame); 
 Return Pack ("h*", $data); 
  function Ord_hex ($data) {$msg = '; 
  $l = strlen ($data); 
  for ($i = 0; $i < $l; $i + +) {$msg. = Dechex (Ord ($data {$i})); 
 return $msg;
  The function send ($k, $msg) {/* $this->send1 ($k, $this->code ($msg), ' all '); */Parse_str ($msg, $g);
  $this->e ($msg);
  $ar =array ();
   if ($g [' type ']== ' Add ') {$this->users[$k] [' Ming ']= $g [' Ming '];
   $ar [' Add ']=true; $ar [' Nrong ']= ' welcome '. $g [' Ming ']. ' Join!
   ';
   $ar [' Users ']= $this->getusers ();
  $key = ' all ';
   }else if ($g [' type ']== ' Ltiao ') {$ar [' Nrong ']= $g [' nr '];
  $key = $g [' key '];
  $msg =json_encode ($ar);
  $this->e ($msg);
  $msg = $this->code ($msg);
  $this->send1 ($k, $msg, $key); Socket_write ($this->users[$k] [' socket '], $msg, strlen ($msg));
  function Getusers () {$ar =array ();
  foreach ($this->users as $k => $v) {$ar [$k]= $v [' Ming '];
 return $ar; function Send1 ($k, $str, $key = ' All ") {if ($key = = ' All ') {foreach ($this->users as $v) {socket_write ($v [' socket ']
   , $str, strlen ($STR));
   }else{if ($k!= $key) socket_write ($this->users[$k] [' socket '], $STR, strlen ($STR));
  Socket_write ($this->users[$key] [' socket '], $STR, strlen ($STR));
  } function Send2 ($ming, $k) {$ar [' Remove ']=true;
  $ar [' RemoveKey ']= $k;
  $ar [' Nrong ']= $ming. ' Exit chat room ';
  $str = $this->code (Json_encode ($ar));
 $this->send1 (False, $str, ' all '); function e ($str) {$path =dirname (__file__). '
  /log.txt '; $str = $str. "
  \ n ";
  Error_log ($STR, 3, $path);
 echo iconv (' Utf-8 ', ' Gbk//ignore ', $str);

 }}?>

I hope this article will help you with your PHP programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.