LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

Web sockets — PHP 实现

admin
2015年7月10日 17:16 本文热度 7007

自十月底,html5 宣布定稿之后,新一轮的关于html的讨论便开始了,现在这里,我也为大家介绍一种html5标准中提到的新技术 websocket,以及他的 php 实现范例。

WebSocketHTML5开始提供的一种浏览器服务器间进行全双工通讯的网络技术。WebSocket通信协议于2011年被IETF定为标准RFC 6455,WebSocketAPIW3C定为标准。

在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

—————-  form wiki

传统的web程序,都遵循这样的执行方式,浏览器发送一个请求,然后服务器端接收这个请求,处理完成浏览器的请求之后,再将处理完成的结果返回给浏览器,然后浏览器处理返回的html,将其呈现给用户。如下图所示:

server

即使后来出现了ajax这样的新的技术,它实际也是使用javascript的api来向服务器发送请求,然后等待相应的数据。也就是说,在浏览器和服务器的交互中,我们每想得到一个得到新的数据(更新页面,获得服务器端的最新状态)就必须要发起一个http请求,建立一条TCP/IP链接,当这次请求的数据被浏览器接收到之后,就断开这条TCP/IP连接。

新的websocket技术,在浏览器端发起一条请求之后,服务器端与浏览器端的请求进行握手应答之后,就建立起一条长久的,双工的长连接,基于这条连接,我们不必做一些轮询就能随时获得服务器端的状态,服务器也不必等待浏览器端的请求才能向用户推送数据,可以在这条连接上随时向以建立websocket连接的用户 push 数据。

这里是 websocket 协议的 RFC 文档。

我这里的实现是基于 php sockets的实现,php socket api.

001<?php
002  class WsServer{
003      public  $socket;
004      public  $socketArray;
005      public  $activatedSocketArray;
006      public function __construct($address,$port){
007        $this->socket =  $this->init($address,$port);
008        if($this->socket == null)
009            exit(1);
010         
011      }
012      private function init($address,$port){
013         $wssocket  = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
014         socket_set_option($wssocket, SOL_SOCKET, SO_REUSEADDR, 1);
015         socket_bind($wssocket,$address,$port);
016         if(socket_listen($wssocket)){
017            $this->p("Socket init success");
018            return $wssocket;
019         }else{
020            $this->p("Socket init failure");
021            exit();
022         }
023          
024      }
025      
026      public function run(){
027        $this->socketArray[] = $this->socket;
028        $write  = NULL;
029        $except = NULL;
030        while (true){
031        $this->activatedSocketArray = $this->socketArray;
032        socket_select($this->activatedSocketArray, $write, $except, null);
033         
034        foreach($this->activatedSocketArray as $s){
035         if($s == $this->socket){
036           $client = socket_accept($this->socket);
037           socket_recv($client, $buffer, 2048, 0);
038          
039           // response a handshake response
040           if(socket_write($client, $this->handshakeResponse($buffer))!== false){
041             $this->p('add a socket into the queue');
042             array_push($this->socketArray, $client);
043            }else{
044               $this->p('error on handshake');
045               $this->errorLog(socket_last_error());
046           }
047        }else{
048            socket_recv($s, $buffer, 2048, 0);
049             
050            $frame = $this->parseFrame($buffer);
051            var_dump($frame);
052            $str  = $this->decode($buffer);
053            $str = $this->frame($str);
054            socket_write($s,$str,strlen($str));
055          }
056        }
057         
058        }
059      }
060      /**
061       *  parse the frame
062       * */
063      private function parseFrame($d){
064        $firstByte = ord(substr($d,0,1));
065        $result =array();
066        $result['FIN'] = $this->getBit($firstByte,1);
067        $result['opcode'] = $firstByte & 15;
068        $result['length'] = ord(substr($d,1,1)) & 127;
069        return $result;
070      }
071      private function getBit($m,$n){
072         return  ($n >> ($m-1)) & 1; 
073      }
074      /*
075       *   build the data frame sent to client by server socket. 
076       *
077       * **/
078      function frame($s){
079        $a = str_split($s, 125);
080        if (count($a) == 1){
081            return "\x81" . chr(strlen($a[0])) . $a[0];
082        }
083        $ns = "";
084        foreach ($a as $o){
085            $ns .= "\x81" . chr(strlen($o)) . $o;
086        }
087        return $ns;
088      }
089      /*
090       * decode the client socket input
091       *
092       * **/
093      function decode($buffer) {
094        $len = $masks = $data = $decoded = null;
095        $len = ord($buffer[1]) & 127;
096       
097        if ($len === 126) {
098            $masks = substr($buffer, 4, 4);
099            $data = substr($buffer, 8);
100        }
101        else if ($len === 127) {
102            $masks = substr($buffer, 10, 4);
103            $data = substr($buffer, 14);
104        }
105        else {
106            $masks = substr($buffer, 2, 4);
107            $data = substr($buffer, 6);
108        }
109         
110        for ($index = 0; $index < strlen($data); $index++) {
111            $decoded .= $data[$index] ^ $masks[$index % 4];
112        }
113        return $decoded;
114      }
115    /*
116     * params @requestHeaders : read from request socket
117     * return an array of request
118     *
119     * */
120    function parseHeaders($requsetHeaders){
121        $resule =array();
122        if (preg_match("/GET (.*) HTTP/"              ,$requsetHeaders,$match)) { $resule['reuqest'] = $match[1]; }
123        if (preg_match("/Host: (.*)\r\n/"             ,$requsetHeaders,$match)) { $result['host'] = $match[1]; }
124        if (preg_match("/Origin: (.*)\r\n/"           ,$requsetHeaders,$match)) { $result['origin'] = $match[1]; }
125        if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/",$requsetHeaders,$match)) { $result['key'] = $match[1]; }
126        return $result;
127         
128    }
129    /*
130     * protocol version : 13
131     * generting the key of handshaking
132     * return encrypted key
133     * */
134    function getKey($requestKey){
135        return base64_encode(sha1($requestKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
136         
137    }
138    /**params @parseRequest : request written in socket
139     * return handshakResponse witten in response socket
140     * */
141    function  handshakeResponse($request){
142        $parsedRequest  = $this->parseHeaders($request);
143        $encryptedKey = $this->getKey($parsedRequest['key']);
144        $response  = "HTTP/1.1 101 Switching Protocol\r\n" .
145                    "Upgrade: websocket\r\n" .
146                    "Connection: Upgrade\r\n" .
147                    "Sec-WebSocket-Accept: " .$encryptedKey. "\r\n\r\n";
148        return $response;
149                     
150    }
151    /*
152     * report last_error in socket
153     *
154     * */
155    function errorLog($ms){
156        echo 'Error:\n'.$ms;
157    }
158    /*
159     * print the log
160     *
161     * */
162    private  function p($e){
163        echo $e."\n";
164    }
165   function test(){
166      $read[] = $this->socket;
167      $write = null;
168      $except = null;
169      socket_select($read, $write, $except,null);
170      var_dump($read);
171   }
172  }
173  $w = new WsServer('localhost',4000);
174  $w->run();
175?>

 

这篇文章中对这里的代码的有些地方做了些相关的解释

这个类主要实现了对websocket的握手回应,将每一个连接成功的websocket加入到一个数组中之后,就能够在服务器端对多个websocket 客户端进行处理。

对websocket的握手请求,在接收到的报文中 会得到一个 Sec-WebSocket-Key 字段,要把“Sec-WebSocket-Key”加上一个魔幻字符串“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”。使用SHA-1加密,之后进行BASE-64编码,将结果做为“Sec-WebSocket-Accept”头的值,返回给客户端。这样就完成了与客户端之间的握手。

之后,就能在服务器端监听客户端发来的请求了,同时也可以操作在服务端的socket句柄,来向浏览器推送消息。


该文章在 2015/7/10 17:16:19 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved