PHP implements socket push technology

不言
Release: 2023-04-02 19:32:01
Original
2131 people have browsed it

This article mainly introduces the socket push technology implemented in PHP. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.

There were already ajax timing requests before the socket appeared. Long polling and other solutions, but none of them can meet the needs, so socket was born.

Socket basic function socket

Summary of commonly used socket functions

Server side: socket_create creates a socket and sets basic parameters

socket_bind binds ip and port number

socket_listen listens

socket_accept client connection

socket_read reads client data

socket_write sends data to a single client

socket_close Close the connection

Client: socket_create Create socket and set basic parameters

socket_connect Connect socket

socket_write Send data to the server

socket_read Read server data

socket_close closes the connection

H5websocketNo more talk, go to the link

OK, start posting the code~

--------- -------------------------------------------------segmentation Line

Server code:

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, NULL); //自动选择来消息的socket 如果是握手 自动选择主机 foreach ($socketArr as $socket){ if ($socket == $this->master){ //主机 $client = socket_accept($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"; //必须以两个回车结尾 $this->log($upgrade); $sent = socket_write($socket, $upgrade, strlen($upgrade)); $this->handshake[$handKey]=true; $this->log("Done handshaking..."); return true; } 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){ //基于websocket version 13 $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, 10, 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; } function frame($s){ $a = str_split($s, 125); 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);
Copy after login

Client code (H5):

  demo  
Copy after login

Then execute php demo.php to open the socket (steal a trick from the operation and maintenance, execute nohup php demo.php under Linux & can be executed in the background) , the browser can open multiple index.html, and communication can be established.

Code analysis:

1. The attribute $sockets array saves each accept connection (I don’t know if this description is correct);

2. Attribute The $handshake array saves whether the connection is in the connected state;

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use Elasticsearch in PHP

##Batch update of PHP

The above is the detailed content of PHP implements socket push technology. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!