php 簡單實現webSocket(demo)
阿新 • • 發佈:2018-12-19
api 需要 bstr lines port peer eat 很多 except
WebSocket 是 HTML5 開始提供的一種在單個 TCP 連接上進行全雙工通訊的協議。
WebSocket 使得客戶端和服務器之間的數據交換變得更加簡單,允許服務端主動向客戶端推送數據。
在 WebSocket API 中,瀏覽器和服務器只需要完成一次握手的動作,瀏覽器和服務器之間就形成了一條快速通道創建持久性的連接,兩者之間就直接可以數據互相傳送。(長連接,循環連接的不算)
現在,很多網站為了實現推送技術,所用的技術都是 Ajax 輪詢。輪詢是在特定的的時間間隔(如每1秒),由瀏覽器對服務器發出HTTP請求,然後由服務器返回最新的數據給客戶端的瀏覽器。
這種傳統的模式帶來很明顯的缺點,即瀏覽器需要不斷的向服務器發出請求,然而HTTP請求可能包含較長的頭部,其中真正有效的數據可能只是很小的一部分,顯然這樣會浪費很多的帶寬等資源。
php應用實現webSocket更多使用workerman或swoole框架.
簡單實現webSocket(demo)
serverSocket.php文件
1 <?php 2 3 class SocketService 4 { 5 private $address; 6 private $port; 7 private $_sockets; 8 public function __construct($address = ‘‘, $port=‘‘) 9View Code{ 10 if(!empty($address)){ 11 $this->address = $address; 12 } 13 if(!empty($port)) { 14 $this->port = $port; 15 } 16 } 17 18 public function service(){ 19 //獲取tcp協議號碼。 20 $tcp= getprotobyname("tcp"); 21 $sock = socket_create(AF_INET, SOCK_STREAM, $tcp); 22 socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1); 23 if($sock < 0) 24 { 25 throw new Exception("failed to create socket: ".socket_strerror($sock)."\n"); 26 } 27 socket_bind($sock, $this->address, $this->port); 28 socket_listen($sock, $this->port); 29 echo "listen on $this->address $this->port ... \n"; 30 $this->_sockets = $sock; 31 } 32 33 public function run(){ 34 $this->service(); 35 $clients[] = $this->_sockets; 36 while (true){ 37 $changes = $clients; 38 $write = NULL; 39 $except = NULL; 40 socket_select($changes, $write, $except, NULL); 41 foreach ($changes as $key => $_sock){ 42 if($this->_sockets == $_sock){ //判斷是不是新接入的socket 43 if(($newClient = socket_accept($_sock)) === false){ 44 die(‘failed to accept socket: ‘.socket_strerror($_sock)."\n"); 45 } 46 $line = trim(socket_read($newClient, 1024)); 47 $this->handshaking($newClient, $line); 48 //獲取client ip 49 socket_getpeername ($newClient, $ip); 50 $clients[$ip] = $newClient; 51 echo "Client ip:{$ip} \n"; 52 echo "Client msg:{$line} \n"; 53 } else { 54 socket_recv($_sock, $buffer, 2048, 0); 55 $msg = $this->message($buffer); 56 //在這裏業務代碼 57 echo "{$key} clinet msg:",$msg,"\n"; 58 fwrite(STDOUT, ‘Please input a argument:‘); 59 $response = trim(fgets(STDIN)); 60 $this->send($_sock, $response); 61 echo "{$key} response to Client:".$response,"\n"; 62 } 63 } 64 } 65 } 66 67 /** 68 * 握手處理 69 * @param $newClient socket 70 * @return int 接收到的信息 71 */ 72 public function handshaking($newClient, $line){ 73 74 $headers = array(); 75 $lines = preg_split("/\r\n/", $line); 76 foreach($lines as $line) 77 { 78 $line = chop($line); 79 if(preg_match(‘/\A(\S+): (.*)\z/‘, $line, $matches)) 80 { 81 $headers[$matches[1]] = $matches[2]; 82 } 83 } 84 $secKey = $headers[‘Sec-WebSocket-Key‘]; 85 $secAccept = base64_encode(pack(‘H*‘, sha1($secKey . ‘258EAFA5-E914-47DA-95CA-C5AB0DC85B11‘))); 86 $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" . 87 "Upgrade: websocket\r\n" . 88 "Connection: Upgrade\r\n" . 89 "WebSocket-Origin: $this->address\r\n" . 90 "WebSocket-Location: ws://$this->address:$this->port/websocket/websocket\r\n". 91 "Sec-WebSocket-Accept:$secAccept\r\n\r\n"; 92 return socket_write($newClient, $upgrade, strlen($upgrade)); 93 } 94 95 /** 96 * 解析接收數據 97 * @param $buffer 98 * @return null|string 99 */ 100 public function message($buffer){ 101 $len = $masks = $data = $decoded = null; 102 $len = ord($buffer[1]) & 127; 103 if ($len === 126) { 104 $masks = substr($buffer, 4, 4); 105 $data = substr($buffer, 8); 106 } else if ($len === 127) { 107 $masks = substr($buffer, 10, 4); 108 $data = substr($buffer, 14); 109 } else { 110 $masks = substr($buffer, 2, 4); 111 $data = substr($buffer, 6); 112 } 113 for ($index = 0; $index < strlen($data); $index++) { 114 $decoded .= $data[$index] ^ $masks[$index % 4]; 115 } 116 return $decoded; 117 } 118 119 /** 120 * 發送數據 121 * @param $newClinet 新接入的socket 122 * @param $msg 要發送的數據 123 * @return int|string 124 */ 125 public function send($newClinet, $msg){ 126 $msg = $this->frame($msg); 127 socket_write($newClinet, $msg, strlen($msg)); 128 } 129 130 public function frame($s) { 131 $a = str_split($s, 125); 132 if (count($a) == 1) { 133 return "\x81" . chr(strlen($a[0])) . $a[0]; 134 } 135 $ns = ""; 136 foreach ($a as $o) { 137 $ns .= "\x81" . chr(strlen($o)) . $o; 138 } 139 return $ns; 140 } 141 142 /** 143 * 關閉socket 144 */ 145 public function close(){ 146 return socket_close($this->_sockets); 147 } 148 } 149 150 $sock = new SocketService(‘127.0.0.1‘,‘9000‘); 151 $sock->run();
web.html 文件
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no"> 6 <title>websocket</title> 7 </head> 8 <body> 9 <input id="text" value=""> 10 <input type="submit" value="send" onclick="start()"> 11 <input type="submit" value="close" onclick="close()"> 12 <div id="msg"></div> 13 <script> 14 /** 15 *0:未連接 16 *1:連接成功,可通訊 17 *2:正在關閉 18 *3:連接已關閉或無法打開 19 */ 20 //創建一個webSocket 實例 21 var webSocket = new WebSocket("ws://127.0.0.1:9000"); 22 23 24 webSocket.onerror = function (event){ 25 onError(event); 26 }; 27 28 // 打開websocket 29 webSocket.onopen = function (event){ 30 onOpen(event); 31 }; 32 33 //監聽消息 34 webSocket.onmessage = function (event){ 35 onMessage(event); 36 }; 37 38 39 webSocket.onclose = function (event){ 40 onClose(event); 41 } 42 43 //關閉監聽websocket 44 function onError(event){ 45 document.getElementById("msg").innerHTML = "<p>close</p>"; 46 console.log("error"+event.data); 47 }; 48 49 function onOpen(event){ 50 console.log("open:"+sockState()); 51 document.getElementById("msg").innerHTML = "<p>Connect to Service</p>"; 52 }; 53 54 function onMessage(event){ 55 console.log("onMessage"); 56 document.getElementById("msg").innerHTML += "<p>response:"+event.data+"</p>" 57 }; 58 59 function onClose(event){ 60 document.getElementById("msg").innerHTML = "<p>close</p>"; 61 console.log("close:"+sockState()); 62 webSocket.close(); 63 } 64 65 function sockState(){ 66 var status = [‘未連接‘,‘連接成功,可通訊‘,‘正在關閉‘,‘連接已關閉或無法打開‘]; 67 return status[webSocket.readyState]; 68 } 69 70 function start(event){ 71 console.log(webSocket); 72 var msg = document.getElementById(‘text‘).value; 73 document.getElementById(‘text‘).value = ‘‘; 74 console.log("send:"+sockState()); 75 console.log("msg="+msg); 76 webSocket.send("msg="+msg); 77 document.getElementById("msg").innerHTML += "<p>request"+msg+"</p>" 78 }; 79 80 function close(event){ 81 webSocket.close(); 82 } 83 </script> 84 </body> 85 </html>View Code
運行結果:
準備工作開啟擴展: php需要打開websocket的配置,在php安裝目錄下的php.ini extension=php_sockets.dll
先執行腳本 例如: php -q serverSocket.php
後執行頁面 例如: http://web.html
php 簡單實現webSocket(demo)