socket基本函数socket
总结下常用的socket函数
服务端: socket_create 创建socket设置基本参数
socket_bind 绑定ip和端口号
socket_listen 监听
socket_accept 客户端的连接
socket_read 读取客户端的数据
socket_write 给单独客户端发送数据
socket_close 关闭连接
客户端:socket_create 创建socket设置基本参数
socket_connect 连接socket
socket_write 给服务端发送数据
socket_read 读取服务端数据
socket_close 关闭连接
h5websocket不多说了,上链接
ok,开始贴代码~
----------------------------------------------------------分割线
服务端代码:
<?php class ws { var $master; var $sockets = array(); var $debug = false;//true为调试模式,输出log日志 var $handshake = array(); function __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, 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);
客户端代码(h5):
<html> <head> <title>demo</title> <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script> </head> <body> <input type="text" id="content"> <input type="button" value="send" id="send"> <script type="text/javascript"> var ws = new websocket(ws://localhost:4000); ws.onopen = function(){ console.log(握手成功); } ws.onmessage = function(e){ console.log(message: + e.data); } ws.onerror = function(){ console.log(error); } $(#send).click(function(){ content = $(#content).val(); console.log(content); ws.send(content); }) </script> </body> </html>
然后执行php demo.php 开启socket(从运维那偷学一招,linux下执行nohup php demo.php &可以在后台执行),浏览器打开多个index.html,就能建立通讯了。
代码解析:
1.属性$sockets数组保存每个accept连接(不知道这么描述对不对);
2.属性$handshake数组保存连接是否在连接状态;
相关推荐:
php socket 服务器框架workerman
php中关于websocket的详细介绍
python中socket模块详解
以上就是详解php实现socket推送技术的详细内容。
