cari
Rumahpembangunan bahagian belakangtutorial phpphp结合html5的websocket通讯的使用方法
php结合html5的websocket通讯的使用方法Jun 08, 2018 pm 04:29 PM
html5phpwebsocketbilik sembang

本篇文章主要介绍php结合html5的websocket通讯的使用方法,感兴趣的朋友参考下,希望对大家有所帮助。

本文实例讲述了php+html5基于websocket实现聊天室的方法,具体如下:

html5的websocket 实现了双向通信,折腾了几天弄了个聊天室,分享给大家

<?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);
 }
}
?>

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP弹出对话框

如何利用php自动执行.sql文件

php中实现视频拍照

Atas ialah kandungan terperinci php结合html5的websocket通讯的使用方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Alat panas

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Penyesuai Pelayan SAP NetWeaver untuk Eclipse

Penyesuai Pelayan SAP NetWeaver untuk Eclipse

Integrasikan Eclipse dengan pelayan aplikasi SAP NetWeaver.

mPDF

mPDF

mPDF ialah perpustakaan PHP yang boleh menjana fail PDF daripada HTML yang dikodkan UTF-8. Pengarang asal, Ian Back, menulis mPDF untuk mengeluarkan fail PDF "dengan cepat" dari tapak webnya dan mengendalikan bahasa yang berbeza. Ia lebih perlahan dan menghasilkan fail yang lebih besar apabila menggunakan fon Unicode daripada skrip asal seperti HTML2FPDF, tetapi menyokong gaya CSS dsb. dan mempunyai banyak peningkatan. Menyokong hampir semua bahasa, termasuk RTL (Arab dan Ibrani) dan CJK (Cina, Jepun dan Korea). Menyokong elemen peringkat blok bersarang (seperti P, DIV),

Muat turun versi mac editor Atom

Muat turun versi mac editor Atom

Editor sumber terbuka yang paling popular