HTML5-The essence is Websocket client, PHP Websocket how to receive data

Source: Internet
Author: User
Tags fread php websocket shuffle sprintf
Class websocketclient{Private $_socket = null;    Public function __construct ($host, $port) {$this->_connect ($host, $port);    Public Function __destruct () {$this->_disconnect (); } Public Function SendData ($data) {//Send actual Data:return fwrite ($this->_socket, $this->en Code ($DATA)) or Die (' Error: '. $errno. ':' .        $ERRSTR);        $wsData = Fread ($this->_socket, 2000);        $retData = Trim ($wsData, Chr (0). chr (255));    return $retData; } Private Function Encode ($data) {$data = Is_array ($data) | | is_object ($DATA)? Json_encode ($data): (String        ) $data;        $len = strlen ($data);        $mask = Array ();        for ($j = 0; $j < 4; $j + +) {$mask [] = Mt_rand (1, 255);        } $head [0] = 129;        if ($len <=) {$head [1] = $len;          } elseif ($len <= 65535) {$split = Str_split (sprintf ('%016b ', $len), 8);  $head [1] = 126;            $head [2] = Bindec ($split [0]);        $head [3] = Bindec ($split [1]);            } else {$split = Str_split (sprintf ('%064b ', $len), 8);            $head [1] = 127;            for ($i = 0; $i < 8; $i + +) {$head [$i + 2] = Bindec ($split [$i]);            } if ($head [2] > 127) {return false;        }} $head [1] + = 128;        $head = Array_merge ($head, $mask);        foreach ($head as $k = + $v) {$head [$k] = Chr ($v);        } $mask _data = ";        for ($j = 0; $j < $len; $j + +) {$mask _data. = Chr (ord ($data [$j]) ^ $mask [$j% 4]); } return Implode (", $head).    $mask _data;        } Private Function _connect ($host, $port) {$key 1 = $this->_generaterandomstring (32);        $key 2 = $this->_generaterandomstring (32);        $key 3 = $this->_generaterandomstring (8, false, true); $Header = "GET ws://". $host. ":" . $port.        "/http/1.1\r\n"; $header. = "Host:". $host. ":" . $port.        "\ r \ n";        $header. = "connection:upgrade\r\n";        $header. = "pragma:no-cache\r\n";        $header. = "cache-control:no-cache\r\n";        $header. = "upgrade:websocket\r\n";        $header. = "sec-websocket-version:13\r\n"; $header. = "user-agent:mozilla/5.0 (Windows NT 6.3;        WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/39.0.2171.95 safari/537.36\r\n ";        $header. = "Accept-encoding:gzip, deflate, sdch\r\n";        $header. = "accept-language:zh-cn,zh;q=0.8\r\n"; $header. = "Sec-websocket-key:". $key 1.        "\ r \ n"; $header. = "Sec-websocket-extensions:permessage-deflate;        Client_max_window_bits\r\n ";        $header. = "\ r \ n";        $this->_socket = Fsockopen ($host, $port, $errno, $ERRSTR, 2); Fwrite ($this->_socket, $header) or Die (' Error: ' $errno. ':' .        $ERRSTR); $response = Fread ($this->_socket, 2000); /** * @todo: Check response here.         Currently not implemented cause "2 key handshake" is already deprecated.    * See:http://en.wikipedia.org/wiki/websocket#websocket_protocol_handshake */return true;    } Private Function _disconnect () {fclose ($this->_socket);  } Private Function _generaterandomstring ($length = ten, $addSpaces = True, $addNumbers = True) {$characters = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz! '        §$%&/() =[]{} ';        $useChars = Array (); Select some random chars:for ($i = 0; $i < $length; $i + +) {$useChars [] = $characters [mt_        Rand (0, strlen ($characters)-1)]; }//Add spaces and numbers:if ($addSpaces = = = True) {Array_push ($useChars, ' ', ', '        ', ' ', ' ', ' ');        if ($addNumbers = = = True) {Array_push ($useChars, rand (0, 9), rand (0, 9), rand (0, 9)); } ShufFle ($useChars);        $randomString = Trim (Implode (', $useChars));        $randomString = substr ($randomString, 0, $length);    return $randomString; }}

Can send an array to the server, how to receive data?

Reply content:

Class websocketclient{Private $_socket = null;    Public function __construct ($host, $port) {$this->_connect ($host, $port);    Public Function __destruct () {$this->_disconnect (); } Public Function SendData ($data) {//Send actual Data:return fwrite ($this->_socket, $this->en Code ($DATA)) or Die (' Error: '. $errno. ':' .        $ERRSTR);        $wsData = Fread ($this->_socket, 2000);        $retData = Trim ($wsData, Chr (0). chr (255));    return $retData; } Private Function Encode ($data) {$data = Is_array ($data) | | is_object ($DATA)? Json_encode ($data): (String        ) $data;        $len = strlen ($data);        $mask = Array ();        for ($j = 0; $j < 4; $j + +) {$mask [] = Mt_rand (1, 255);        } $head [0] = 129;        if ($len <=) {$head [1] = $len;          } elseif ($len <= 65535) {$split = Str_split (sprintf ('%016b ', $len), 8);  $head [1] = 126;            $head [2] = Bindec ($split [0]);        $head [3] = Bindec ($split [1]);            } else {$split = Str_split (sprintf ('%064b ', $len), 8);            $head [1] = 127;            for ($i = 0; $i < 8; $i + +) {$head [$i + 2] = Bindec ($split [$i]);            } if ($head [2] > 127) {return false;        }} $head [1] + = 128;        $head = Array_merge ($head, $mask);        foreach ($head as $k = + $v) {$head [$k] = Chr ($v);        } $mask _data = ";        for ($j = 0; $j < $len; $j + +) {$mask _data. = Chr (ord ($data [$j]) ^ $mask [$j% 4]); } return Implode (", $head).    $mask _data;        } Private Function _connect ($host, $port) {$key 1 = $this->_generaterandomstring (32);        $key 2 = $this->_generaterandomstring (32);        $key 3 = $this->_generaterandomstring (8, false, true); $Header = "GET ws://". $host. ":" . $port.        "/http/1.1\r\n"; $header. = "Host:". $host. ":" . $port.        "\ r \ n";        $header. = "connection:upgrade\r\n";        $header. = "pragma:no-cache\r\n";        $header. = "cache-control:no-cache\r\n";        $header. = "upgrade:websocket\r\n";        $header. = "sec-websocket-version:13\r\n"; $header. = "user-agent:mozilla/5.0 (Windows NT 6.3;        WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/39.0.2171.95 safari/537.36\r\n ";        $header. = "Accept-encoding:gzip, deflate, sdch\r\n";        $header. = "accept-language:zh-cn,zh;q=0.8\r\n"; $header. = "Sec-websocket-key:". $key 1.        "\ r \ n"; $header. = "Sec-websocket-extensions:permessage-deflate;        Client_max_window_bits\r\n ";        $header. = "\ r \ n";        $this->_socket = Fsockopen ($host, $port, $errno, $ERRSTR, 2); Fwrite ($this->_socket, $header) or Die (' Error: ' $errno. ':' .        $ERRSTR); $response = Fread ($this->_socket, 2000); /** * @todo: Check response here.         Currently not implemented cause "2 key handshake" is already deprecated.    * See:http://en.wikipedia.org/wiki/websocket#websocket_protocol_handshake */return true;    } Private Function _disconnect () {fclose ($this->_socket);  } Private Function _generaterandomstring ($length = ten, $addSpaces = True, $addNumbers = True) {$characters = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz! '        §$%&/() =[]{} ';        $useChars = Array (); Select some random chars:for ($i = 0; $i < $length; $i + +) {$useChars [] = $characters [mt_        Rand (0, strlen ($characters)-1)]; }//Add spaces and numbers:if ($addSpaces = = = True) {Array_push ($useChars, ' ', ', '        ', ' ', ' ', ' ');        if ($addNumbers = = = True) {Array_push ($useChars, rand (0, 9), rand (0, 9), rand (0, 9)); } ShufFle ($useChars);        $randomString = Trim (Implode (', $useChars));        $randomString = substr ($randomString, 0, $length);    return $randomString; }}

Can send an array to the server, how to receive data?

Http://www.workerman.net/workerman-chat
Can look at this, php written websocket chat room, customer service function can actually be used inside the single chat function. Someone uses it to implement a passer-by, including web pages and client software.
Development manual: Http://workerman.net/gatewaydoc/
demo:http://chat.workerman.net/

Baidu on the PHP websocket tutorial has enough, you can go to see.

Socket_read Read

Resolved thank you very much for your answers.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.