Execution method: First modify the IP of server.php and index.html Execute [PHP path]\php.exe] [file path]\server.php] from the command line Then open index.html through the browser
- Include ' websocket.class.php ';
- $config =array (
- ' Address ' = ' 192.168.0.200 ',
- ' Port ' = ' 8000 ',
- ' Event ' = ' wsevent ',//function name of the callback function
- ' Log ' =>true,
- );
- $websocket = new WebSocket ($config);
- $websocket->run ();
- function Wsevent ($type, $event) {
- Global $websocket;
- if (' in ' = = $type) {
- $websocket->log (' Customer Entry ID: ' $event [' K ']);
- }elseif (' out ' = = $type) {
- $websocket->log (' Customer exit ID: ' $event [' K ']);
- }elseif (' msg ' = = $type) {
- $websocket->log ($event [' K ']. ' Message: '. $event [' msg ']);
- Roboot ($event [' sign '], $event [' msg '];
- }
- }
- function Roboot ($sign, $t) {
- Global $websocket;
- Switch ($t)
- {
- Case ' Hello ':
- $show = ' hello,git @ OSC ';
- Break
- Case ' name ':
- $show = ' Robot ';
- Break
- Case ' time ':
- $show = ' Current time: '. Date (' y-m-d h:i:s ');
- Break
- Case ' goodbye ':
- $show = ' (^_^)/~~ goodbye ';
- $websocket->write ($sign, ' Robot: '. $show);
- $websocket->close ($sign);
- Return
- Break
- Case ' King of the Land Tiger ':
- $array = Array (' Chicken stew mushroom ', ' Pagoda Quake River Demon ', ' grain is hard ');
- $show = $array [rand (0,2)];
- Break
- Default
- $show = ' (⊙o⊙?) Do not understand, you can try to say: Hello,name,time, Goodbye, the king of the Land Tiger.
- }
- $websocket->write ($sign, ' Robot: '. $show);
- }
- ?>
Copy Code
-
- Websocket_test
- <li>=======websocket======<li>
Copy Code
- /*
- Create Class WebSocket ($config);
- $config structure:
- $config =array (
- ' Address ' = ' 192.168.0.200 ',//Bind addresses
- ' Port ' = ' 8000 ',//Bind port
- ' Event ' = ' wsevent ',//function name of the callback function
- ' Log ' =>true,//command line display record
- );
- callback function returns data format
- function Wsevent ($type, $event)
- There are three types of string events $type:
- In Client Access
- Out Client Disconnects
- MSG Client message arrives
- are lowercase
- $event Array
- $event [' K '] userid with built-in user list;
- $event [' sign '] customer logo
- $event the message received by [' msg '] $type = ' msg '
- Method:
- Run ()
- Search (Mark) traversal to get the ID of the indicator
- Close (Mark) Disconnect
- Write (flag, message) push information
- Idwrite (ID, info) push information
- Property:
- $users Customer List
- Structure:
- $users =array (
- [User Id]=>array (' socket ' =>[indicator], ' hand ' =[if handshake-boolean value]),
- [User Id]=>arr .....
- )
- */
- Class websocket{
- Public $log;
- Public $event;
- Public $signets;
- Public $users;
- Public $master;
- Public function __construct ($config) {
- if (substr (Php_sapi_name (), 0, 3)!== ' CLI ') {
- Die ("Run through command-line mode!");
- }
- Error_reporting (E_all);
- Set_time_limit (0);
- Ob_implicit_flush ();
- $this->event = $config [' event '];
- $this->log = $config [' Log '];
- $this->master= $this->websocket ($config [' address '], $config [' Port '];
- $this->sockets=array (' s ' = = $this->master);
- }
- function WebSocket ($address, $port) {
- $server = Socket_create (Af_inet, Sock_stream, sol_tcp);
- Socket_set_option ($server, Sol_socket, SO_REUSEADDR, 1);
- Socket_bind ($server, $address, $port);
- Socket_listen ($server);
- $this->log (' Start listening: ' $address. ': '. $port);
- return $server;
- }
- function Run () {
- while (true) {
- $changes = $this->sockets;
- @socket_select ($changes, $write =null, $except =null,null);
- foreach ($changes as $sign) {
- if ($sign = = $this->master) {
- $client =socket_accept ($this->master);
- $this->sockets[]= $client;
- $user = Array (
- ' Socket ' = $client,
- ' Hand ' =>false,
- );
- $this->users[] = $user;
- $k = $this->search ($client);
- $eventreturn = Array (' k ' = = $k, ' sign ' = = $sign);
- $this->eventoutput (' in ', $eventreturn);
- }else{
- $len =socket_recv ($sign, $buffer, 2048,0);
- $k = $this->search ($sign);
- $user = $this->users[$k];
- if ($len <7) {
- $this->close ($sign);
- $eventreturn = Array (' k ' = = $k, ' sign ' = = $sign);
- $this->eventoutput (' Out ', $eventreturn);
- Continue
- }
- if (! $this->users[$k [' hand ']) {//No Handshake for handshake
- $this->handshake ($k, $buffer);
- }else{
- $buffer = $this->uncode ($buffer);
- $eventreturn = Array (' k ' = = $k, ' sign ' = = $sign, ' msg ' = $buffer);
- $this->eventoutput (' msg ', $eventreturn);
- }
- }
- }
- }
- }
- function Search ($sign) {//Pass ID traversal
- foreach ($this->users as $k = + $v) {
- if ($sign = = $v [' socket ']
- return $k;
- }
- return false;
- }
- function Close ($sign) {//Disconnect by marking
- $k =array_search ($sign, $this->sockets);
- Socket_close ($sign);
- unset ($this->sockets[$k]);
- unset ($this->users[$k]);
- }
- function handshake ($k, $buffer) {
- $buf = substr ($buffer, Strpos ($buffer, ' Sec-websocket-key: ') +18);
- $key = Trim (substr ($buf, 0,strpos ($buf, "\ r \ n")));
- $new _key = Base64_encode (SHA1 ($key. ") 258eafa5-e914-47da-95ca-c5ab0dc85b11 ", true));
- $new _message = "http/1.1 101 switching protocols\r\n";
- $new _message. = "upgrade:websocket\r\n";
- $new _message. = "sec-websocket-version:13\r\n";
- $new _message. = "connection:upgrade\r\n";
- $new _message. = "Sec-websocket-accept:". $new _key. "\r\n\r\n";
- Socket_write ($this->users[$k [' socket '], $new _message,strlen ($new _message));
- $this->users[$k] [' Hand ']=true;
- return true;
- }
- function Uncode ($STR) {
- $mask = Array ();
- $data = ";
- $msg = Unpack (' h* ', $str);
- $head = substr ($msg [1],0,2);
- if (Hexdec ($head beckham) = = = 8) {
- $data = false;
- }else if (Hexdec ($head beckham) = = = 1) {
- $mask [] = Hexdec (substr ($msg [1],4,2));
- $mask [] = Hexdec (substr ($msg [1],6,2));
- $mask [] = Hexdec (substr ($msg [1],8,2));
- $mask [] = Hexdec (substr ($msg [1],10,2));
- $s = 12;
- $e = strlen ($msg [1])-2;
- $n = 0;
- for ($i = $s; $i <= $e; $i + = 2) {
- $data. = Chr ($mask [$n%4]^hexdec (substr ($msg [1], $i, 2)));
- $n + +;
- }
- }
- return $data;
- }
- function code ($MSG) {
- $msg = preg_replace (Array ('/\r$/', '/\n$/', '/\r\n$/',), ', $msg);
- $frame = Array ();
- $frame [0] = ' 81 ';
- $len = strlen ($msg);
- $frame [1] = $len <16? ' 0 '. Dechex ($len):d Echex ($len);
- $frame [2] = $this->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;
- }
- function Idwrite ($id, $t) {//push information by ID
- if (! $this->users[$id [' socket ']) {return false;} No sign of that.
- $t = $this->code ($t);
- Return Socket_write ($this->users[$id [' socket '], $t, strlen ($t));
- }
- function Write ($k, $t) {//By marking push information
- $t = $this->code ($t);
- Return Socket_write ($k, $t, strlen ($t));
- }
- function Eventoutput ($type, $event) {//Event callback
- Call_user_func ($this->event, $type, $event);
- }
- function log ($t) {//console output
- if ($this->log) {
- $t = $t. " \ r \ n ";
- Fwrite (STDOUT, Iconv (' Utf-8 ', ' Gbk//ignore ', $t));
- }
- }
- }
Copy Code |