Php+websoket implementation of the Chat room sample code (with source)

Source: Internet
Author: User
Tags php websocket
This article mainly introduces the Php+websoket build Chatserver example (with source) data, here to organize the detailed code, the need for small partners can refer to.

Recently in the company's use of live between the establishment of a graphic live broadcast between the chatsever, the study of the HTML5 WebSocket realized two-way communication, according to the experience of predecessors toss a few days to get a chat room, to send pictures, send QQ expression, group chat private chat and other functions, Specially to share to you novice reference study, Daniel can ignore.

Front End: client.html

<!doctype html>

<?phperror_reporting (e_all ^ e_notice); Ob_implicit_flush (); $sk =new Sock (' 127.0.0.1 ', 8000); $sk->run (); class  sock{public $sockets, public $users, public $master; Private $SDA =array ();//Received Data Private $slen =array ();//Data total length private $sjen =array ();//The length of the received data private $ar =array ();/  Encryption key Private $n =array (); Public function __construct ($address, $port) {$this->master= $this->websocket ($address, $port); $this Sockets=array ($this->master); The function run () {while (true) {$changes = $this->sockets; $write =null; $except =null; Socket_select ($changes, $write, $ Except,null);  foreach ($changes as $sock) {if ($sock = = $this->master) {$client =socket_accept ($this->master);  $key =uniqid ();  $this->sockets[]= $client; $this->users[$key]=array (' socket ' = $client, ' shou ' =>false);  }else{$len = 0;  $buffer = ";  do{$l =socket_recv ($sock, $buf, 1000,0);  $len + = $l;  $buffer. = $buf;  }while ($l ==1000);  $k = $this->search ($sock);  if ($len <7) {$this->send2 ($k); Continue } if (! $this->users[$k [' Shou ']) {$this->woshou ($k, $buffer);  }else{$buffer = $this->uncode ($buffer, $k);  if ($buffer ==false) {continue;  } $this->send ($k, $buffer); }}}}} function close ($k) {socket_close ($this->users[$k] [' socket ']), unset ($this->users[$k]); $this->socket S=array ($this->master); foreach ($this->users as $v) {$this->sockets[]= $v [' socket '];} $this->e ("Key: $k close");  The 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 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 [' socket '], $new _message,strlen ($new _message)); $this->users[$k] [' Shou ']=true;  return true;  } function Uncode ($str, $key) {$mask = array ();  $data = "; $msg = Unpack (' h* ', $str);  $head = substr ($msg [1],0,2); if ($head = = ' Bayi ' &&!isset ($this->slen[$key]) {$len =substr ($msg [1],2,2); $len =hexdec ($len); if (substr ($ msg[1],2,2) = = ' Fe ') {$len =substr ($msg [1],4,4); $len =hexdec ($len); $msg [1]=substr ($msg [1],4];} else if (substr ($msg [1],2,2) = = ' ff ') {$len =substr ($msg [1],4,16); $len =hexdec ($len); $msg [1]=substr ($msg [1],16];} $  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; $n = 0; }else if ($this->slen[$key] > 0) {$len = $this->slen[$key]; $mask = $this->ar[$key]; $n = $this->n[$key]; $s = 0; } $e = strlen ($msg [1])-2;  for ($i = $s; $i <= $e; $i + = 2) {$data. = Chr ($mask [$n%4]^hexdec (substr ($msg [1], $i, 2)));  $n + +;  } $dlen =strlen ($data); if ($len > 255 && $len > $dlen +intval ($this->sjen[$key]) {$this->ar[$key]= $mask; $this->slen[$ Key]= $len; $this->sjen[$key]= $dlen +intval ($this->sjen[$key]); $this->sda[$key]= $this->sda[$key]. $data; $this->n[$key]= $n; return false; }else{unset ($this->ar[$key], $this->slen[$key], $this->sjen[$key], $this->n[$key]); $data = $this sda[$key]. $data; unset ($this->sda[$key]); return $data;  }} function code ($msg) {$frame = array ();  $frame [0] = ' 81 '; $len = strlen ($msg); if ($len < 126) {$frame [1] = $len <16? ' 0 '. Dechex ($len):d Echex ($len); }else if ($len < 65025) {$s =dechex ($len); $frame [1]= ' 7e '. Str_repeat (' 0 ', 4-strlen ($s)). $s;}  else{$s =dechex ($len); $frame [1]= ' 7f '. Str_repeat (' 0 ', 16-strlen ($s)). $s;} $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; }//user joins function Send ($k, $msg) {parse_str ($msg, $g); $ar =array (); if ($g [' type ']== ' Add ') {$this->users[$k] [' Name ']= $g [' Ming ']; $ar [' type ']= ' add '; $ar [' name ']= $g [' Ming ']; $key = ' all '; }else{$ar [' Nrong ']= $g [' nr ']; $key = $g [' key '];} $this->send1 ($k, $ar, $key); } function Getusers () {$ar =array (); foreach ($this->users as $k = + $v) {$ar []=array (' Code ' + $k, ' name ' = * = $v [' Name ']); } return $ar; }//$k sender's code $key recipient's Code function send1 ($k, $ar, $key = ' all ') {$ar [' code1 ']= $key; $ar [' Code ']= $k; $ar [' Time ']=date (' m-d h:i:s '); $str = $this->code (Json_encode ($ar)); if ($key = = ' All ') {$users = $this-&Gt;users; if ($ar [' type ']== ' Add ') {$ar [' type ']= ' Madd '; $ar [' Users ']= $this->getusers (); $str 1 = $this->code (Json_encode ($ AR)); Socket_write ($users [$k] [' socket '], $str 1,strlen ($str 1)); Unset ($users [$k]); } foreach ($users as $v) {socket_write ($v [' socket '], $STR, strlen ($STR));}} else{socket_write ($this->users[$k [' socket '], $STR, strlen ($STR)), Socket_write ($this->users[$key [' socket ' ], $str, strlen ($STR)); }}//user exits function Send2 ($k) {$this->close ($k); $ar [' Type ']= ' rmove '; $ar [' Nrong ']= $k; $this->send1 (False, $ar, ' All '); } function e ($STR) {//$path =dirname (__file__). ' /log.txt '; $str = $str. " \ n "; Error_log ($STR, 3, $path); echo iconv (' Utf-8 ', ' Gbk//ignore ', $str); }}?>

Many children's shoes reaction with my source code project or error, can not run, say detailed installation deployment steps.

First extract the downloaded source code into the Web directory, such as mine is Applications/xampp/xamppfiles/htdocs/phpb/websocket,

Path

Then use the Command line tool CD to enter this directory and run the command:

PHP websocket.php

Run:

Command-line Operations

Then open the Apache server and access the http://localhost/phpb/websocket/client.html in the browser

Run:

SOURCE Link: Websoket-php-chatsever_jb51.rar

Related Article

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.