PHP implementation of socket push Technology example explained

Source: Internet
Author: User
Tags log log
The following small series for you to share a PHP implementation of the socket push Technology example, has a good reference value, I hope to be helpful to everyone. Let's take a look at it with a little knitting.

There are AJAX timing requests before the socket, long polling and other scenarios, but can not meet the needs of the socket is the application of the birth.

Socket BASIC Function socket

Summarize the common socket functions

Service side: socket_create Create socket settings Basic parameters

Socket_bind binding IP and port number

Socket_listen Monitoring

Socket_accept Connections to clients

Socket_read reading the client's data

Socket_write sending data to individual clients

Socket_close Closing the connection

client:socket_create Create socket settings Basic parameters

Socket_connect connecting sockets

Socket_write sending data to the server

Socket_read Reading service-side data

Socket_close Closing the connection

H5websocket not much to say, on the link

OK, start pasting code ~

----------------------------------------------------------Split Line

Service-Side code:

<?phpclass WS {var $master; var $sockets = array (), var $debug = false;//true for debug mode, output log log var $handshake = array (); f Unction __construct ($address, $port) {$this->master=socket_create (af_inet, Sock_stream, sol_tcp) or Die ("socket_ Create () failed "); Socket_set_option ($this->master, Sol_socket, SO_REUSEADDR, 1) or Die ("Socket_option () failed"); Socket_bind ($this->master, $address, $port) or Die ("Socket_bind () failed");  Socket_listen ($this->master,20) or Die ("Socket_listen () failed"); $this->sockets[] = $this->master; $this->say ("Server Started:". Date (' y-m-d h:i:s ')); $this->say ("Listening on:". $address. "Port". $port); $this->say ("Master socket:" $this->master. "  \ n "); while (true) {$SOCKETARR = $this->sockets; $write = null; $except = null; Socket_select ($SOCKETARR, $write, $except, NUL L); Automatically select the socket for the message if the handshake is automatically selected by the host foreach ($socketArr as $socket) {if ($socket = = $this->master) {//Host $client = Socket_ac  Cept ($this->master); if ($clieNT < 0) {$this->log ("Socket_accept () failed");  Continue  } else{$this->connect ($client);  }} else {$bytes = @socket_recv ($socket, $buffer, 2048,0);  if ($bytes = = 0) {$this->disconnect ($socket);  } else{$key = Array_search ($socket, $this->sockets); if (Empty ($this->handshake) | |!isset ($this->handshake[$key]) | |! $this->handshake[$key]) {$this  Dohandshake ($socket, $buffer, $key);  } else{$buffer = $this->decode ($buffer); Echo $buffer.  Php_eol;  $key = Array_search ($socket, $this->sockets);  $arr = $this->sockets;  Array_shift ($arr);  foreach ($arr as $s) {$this->send ($s, $buffer);  }}}}}}} function Send ($client, $msg) {$msg = $this->frame ($msg); Socket_write ($client, $msg, strlen ($msg));} Function Connect ($socket) {Array_push ($this->sockets, $socket) $this->say ("\ n". $socket. "connected!"); $this->say (Date ("y-n-d h:i:s")); } function DisConnect ($socket) {$index = Array_search ($socket, $this->sockets);Socket_close ($socket); $this->say ($socket. "disconnected!"); if ($index >= 0) {echo ' unset index is: '. Php_eol; unset ($this->sockets[$index]); }} function Dohandshake ($socket, $buffer, $handKey) {$this->log ("\nrequesting handshake ..."); $this->log ($buffer); List ($resource, $host, $origin, $key) = $this->getheaders ($buffer); $this->log ("handshaking ...");  $upgrade = "http/1.1 101 switching protocol\r\n".  "Upgrade:websocket\r\n".  "Connection:upgrade\r\n". "Sec-websocket-accept:". $this->calckey ($key). "\r\n\r\n"; Must end with two carriage returns $this->log ($upgrade); $sent = Socket_write ($socket, $upgrade, strlen ($upgrade)); $this->handshake[$handKey]=true; $this->log ("Done handshaking ..."); return true;  The function getheaders ($req) {$r = $h = $o = $key = null, if (Preg_match ("/get (. *) http/", $req, $match)) {$r = $match [1];  if (Preg_match ("/host: (. *) \r\n/", $req, $match)) {$h = $match [1];} if (Preg_match ("/origin: (. *) \r\n/", $req, $match)) {$o = $match [1];} if (Preg_match ("/sec-websocket-key: (. *) \r\n/", $req, $match)) {$key = $match [1];} return Array ($r, $h, $o, $key); } function Calckey ($key) {//Based on websocket version $accept = Base64_encode (SHA1 ($key. ' 258eafa5-e914-47da-95ca-c5ab0dc85b11 ', true)); return $accept; } function decode ($buffer) {$len = $masks = $data = $decoded = null, $len = Ord ($buffer [1]) & 127; if ($len = = = 126)  {$masks = substr ($buffer, 4, 4); $data = substr ($buffer, 8);}  else if ($len = = = 127) {$masks = substr ($buffer, ten, 4); $data = substr ($buffer, 14);}  else {$masks = substr ($buffer, 2, 4), $data = substr ($buffer, 6);} for ($index = 0; $index < strlen ($data); $index + +) {$decoded. = $data [$index] ^ $masks [$index% 4];} return $decoded; The function frame ($s) {$a = Str_split ($s), if (count ($a) = = 1) {return "\x81". Chr (strlen ($a [0]). $a [0];} $ns = "" ; foreach ($a as $o) {$ns. = "\x81". Chr (strlen ($o)). $o;} return $ns; } function Say ($msg = "") {echo $msg. \ n "; } function log ($msg ="") {if ($this->debug) {echo $msg. \ n "; }}} new WS (' localhost ', 4000);

Client code (H5):


Then execute PHP demo.php Open the socket (from the operation of the steal learn a trick, Linux execution nohup php demo.php & can be executed in the background), the browser opens multiple index.html, you can establish communication.

Code parsing:

1. Attribute $sockets array Save each accept connection (do not know the description is correct);

2. Attribute $handshake array to save the connection status;

This PHP implementation of the socket Push Technology example is a small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support PHP Chinese network.

Articles you may be interested in:

How to get a shared delivery address in PHP

THINKPHP5 Project steps in cloud Virtualization host deployment

Phpcrawl Crawler Library to implement a cool dog song list of ways to explain

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.