金沙官网线上HTML5_07之WebSocket

1、HTML5新特性之WebSocket:
 ①HTTP协议的不足:基于“请求——响应”模型,只有在客户端发送请求后,服务器才会给予响应;对于实时的股票走势图,以及聊天通讯等无法满足需求;
 ②解决方案:setInterval+AJAX:心跳请求;
  问题:过于频繁对服务器压力过大,频率过低则信息获取延迟;
 ③最佳解决方案——WebSocket协议:
  基于“广播——收听”模型,客户端连接到服务器后不再断开,服务器有了消息随时发送给客户端,客户端也可以不停地给服务器发送消息;
  不足:客户端和服务器是永久连接,服务器端可容纳的连接数是有限的;
 ④WebSocket应用需要服务器端和客户端都使用WebSocket协议;
 ⑤socket_server.php:

<?php

  $address = "127.0.0.1";

  $port = 9999; //调试的时候,可以多换端口来测试程序!

  set_time_limit(0);

  $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

  socket_set_block($sock);

  socket_bind($sock, $address, $port);

  socket_listen($sock, 4);

 

  do

  {

      echo "Waiting for Connection...n";

      $msgsock = socket_accept($sock);

      echo "Waiting for Request...n";

      $buf = socket_read($msgsock, 8192);     //读取请求

      echo "Request Received: $bufn";

      $response = hand_shake($buf);

      socket_write($msgsock,$response,strlen($response)); //发送响应

      //正式开始通信...

      $buf = socket_read($msgsock, 8192);

      for($i=0; $i<5; $i++){

          $msg = "WELCOME $in";

          $msg = code($msg);

          sleep(1);

          socket_write($msgsock, $msg, strlen($msg));

      }

      socket_close($msgsock);

  } while (true);

  socket_close($sock);

 

  function hand_shake($buf){

      $buf  = substr($buf,strpos($buf,'Sec-WebSocket-Key:')+18);

      $key  = trim(substr($buf,0,strpos($buf,"rn")));

      $new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));

      $new_message = "HTTP/1.1 101 Switching Protocolsrn";

      $new_message .= "Upgrade: websocketrn";

      $new_message .= "Sec-WebSocket-Version: 13rn";

      $new_message .= "Connection: Upgradern";

      $new_message .= "Sec-WebSocket-Accept: " . $new_key . "rnrn";

      return $new_message;

  }

  function code($msg){

      $msg = preg_replace(array('/r$/','/n$/','/rn$/',), '', $msg);

      $frame = array();

      $frame[0] = '81';

      $len = strlen($msg);

      $frame[1] = $len<16?'0'.dechex($len):dechex($len);

      $frame[2] = 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;

  }

 

本文由金沙官网线上发布于Web前端,转载请注明出处:金沙官网线上HTML5_07之WebSocket

您可能还会对下面的文章感兴趣: