How can I write PHPsocket code to accept the data sent from the client websocket?

Source: Internet
Author: User
Tags php websocket set socket socket error usleep
How can I write the PHPsocket code to accept the data sent from the client websocket? how can I write the PHP socket code to accept the data sent from the client websocket?


Baidu hasn't seen the complete code for half a day, and it's not a good tutorial.


Reply to discussion (solution)

We recommend that you directly use workerman, which has a ready-made php websocket server and has excellent performance.
The following is an online demo of the websocket of three workerman workers. The source code and comments on the official website are also detailed. it is worth reading.

Http://kedou.workerman.net/
Http://www.workerman.net: 55151/
Http://flap.workerman.net/

We recommend that you directly use workerman, which has a ready-made php websocket server and has excellent performance.
The following is an online demo of the websocket of three workerman workers. The source code and comments on the official website are also detailed. it is worth reading.

Http://kedou.workerman.net/
Http://www.workerman.net: 55151/
Http://flap.workerman.net/


I have never used the data sent from the client, and I have to change it myself .. I want to write native

Who can help write a native one.

Ready-made online

/*** TCP operation base class * @ package SHIT \ Protocol * @ see \ SHIT \ Object */class TCPv4 extends \ X \ Core \ Object {/*** socket handle * @ var resource */protected $ rLink = null; /*** constructor ** @ param string $ ip address * @ param int $ port number ** @ throws \ X \ Exception \ login action */public function _ construct ($ ip, $ port) {$ this-> rLink = @ socket_create (AF_INET, SOCK_STREAM, SOL_TCP); if (false ===$ this-> rLink) {$ this-> rLink = Null; $ this-> SetSocketError (_ LINE _); throw new \ X \ Exception \ Error ($ this-> sError, $ this-> iErrno );} // Set connection timeout to 1 second if (! $ This-> SetSendTimeout (1) {$ this-> Close (); throw new \ X \ Exception \ Error ($ this-> sError, $ this-> iErrno);} // echo 'sssssssssssss'; if (! @ Socket_connect ($ this-> rLink, $ ip, $ port) {$ this-> SetSocketError (_ LINE _); $ this-> Close (); throw new \ X \ Exception \ Error ($ this-> sError, $ this-> iErrno);} // var_dump ($ this-> rLink); exit; if (! $ This-> SetSendTimeout (1) |! $ This-> SetRecvTimeout (3) {$ this-> Close (); throw new \ X \ Exception \ Error ($ this-> sError, $ this-> iErrno);}/*** destructor */public function _ destruct () {$ this-> Close ();} /*** send data ** @ param string $ buffer cache of the data to be sent * @ param int $ flags parameter. the default value is 0 ** @ return bool. return true if the data is successfully sent, otherwise, false */public function Send ($ buffer, $ flags = 0) {$ buffer = strval ($ buffer); $ bufLen = strlen ($ buffer ); if ($ bufLen <= 0 ){ Return true;} $ finishIndex = 0; $ bytes = null; $ zeroTimes = 0; do {if ($ finishIndex> 0) {usleep (100 );} $ bytes = @ socket_send ($ this-> rLink, substr ($ buffer, $ finishIndex), $ bufLen-$ finishIndex, $ flags); if (false = $ bytes) {$ this-> SetSocketError (_ LINE _); return false;} else if ($ bytes <= 0) {++ $ zeroTimes; if ($ zeroTimes> 100) {$ this-> SetError ('send data 0 bytes more than 100 time S ', _ LINE _); return false ;}} else {$ finishIndex + = $ bytes ;}} while ($ finishIndex <$ bufLen); return true ;} /*** get data ** @ param string & $ buffer stores the cache of received data (note: The function clears the cache and then stores the received data) * @ param int $ length the length of the received data * @ param int $ flags parameter. the default value is 0 ** @ return bool. return true if the message is sent successfully, otherwise, false */public function Recv (& $ buffer, $ length, $ flags = 0) {$ length = intval ($ length); if ($ length <= 0) is returned) {return true;} $ buf Fer = ''; $ bytes =-1; $ cache =''; $ zeroTimes = 0; do {if ($ bytes> 0) {usleep (100 );} $ bytes = @ socket_recv ($ this-> rLink, $ cache, $ length, $ flags); if (false ===$ bytes) {$ this-> SetSocketError (_ LINE _); return false;} else if ($ bytes <= 0) {++ $ zeroTimes; if ($ zeroTimes> 100) {$ this-> SetError ('receive data 0 bytes more than 100 times ', _ LINE _); return false ;}} else {$ length-= $ byte S;} $ buffer. = $ cache;} while ($ length> 0); return true;}/*** set the sending timeout time * @ param int $ seconds, the default value is 1 * @ param int $ microseconds. the default value is 0 ** @ return bool. true is returned if sending is successful. otherwise, false */public function SetSendTimeout ($ seconds = 1, $ microseconds = 0) {$ seconds = intval ($ seconds); $ microseconds = intval ($ microseconds); if ($ seconds <0 | $ microseconds <0) {$ seconds = 1; $ microseconds = 0;} if (! Socket_set_option ($ this-> rLink, SOL_SOCKET, SO_SNDTIMEO, array ("sec" => $ seconds, "usec" => $ microseconds ))) {$ this-> SetSocketError (_ LINE _); return false;} return true;}/*** set the receiving timeout time * @ param int $ seconds, the default value is 3 * @ param int $ microseconds. the default value is 0 ** @ return bool. return true if the message is sent successfully. Otherwise, return false */public function SetRecvTimeout ($ seconds = 3, $ microseconds = 0) {$ seconds = intval ($ seconds); $ microseconds = Intval ($ microseconds); if ($ seconds <0 | $ microseconds <0) {$ seconds = 3; $ microseconds = 0;} if (! Socket_set_option ($ this-> rLink, SOL_SOCKET, SO_RCVTIMEO, array ("sec" => $ seconds, "usec" => $ microseconds ))) {$ this-> SetSocketError (_ LINE _); return false;} return true ;} /*** Close the connected socket ** @ return void */protected function Close () {if (is_resource ($ this-> rLink )) {socket_close ($ this-> rLink); $ this-> rLink = null ;}} /*** set Socket Error * @ param int $ line error line ** @ return void */protected function SetSocketError ($ line) {$ code = socket_last_error (); $ msg = socket_strerror ($ code); $ this-> SetError ("[$ code] $ msg", $ line );} /*** get undefined data * @ param string & $ buffer stores the cache of the received data (note: The function clears the cache and then stores the received data) * @ param int $ flags parameter. the default value is 0 ** @ return bool. true is returned if sending is successful. otherwise, false */public function RecvForDontKnowLength (& $ buffer, $ flags = 0) is returned) {$ buffer = ''; $ bytes =-1; $ cache =''; do {if ($ bytes> 0) {usleep (100 );} $ bytes = @ socket_recv ($ this-> rLink, $ cache, 65535, $ flags); if (false ===$ bytes) {$ this-> SetSocketError (_ LINE _); return false;} else if ($ bytes <65535) {$ buffer. = $ cache; break;} $ buffer. = $ cache ;}while (true); return true ;}}



An example of how to get the device status: call socket and obtain data
/** Device logout **/private function DeviceLogout () {$ serverIp = $ _ SERVER ['server _ ADDR ']; // server IP $ header = "\ x01 \ x00 \ x30 \ x04 ". pack ('N', 0); $ buffer = pack ('N', $ this-> deviceID ). $ serverIp. "\ 0"; $ buffer = $ header. pack ('N', 8 + strlen ($ buffer )). $ buffer; $ this-> package = $ buffer ;}


/*** Send data packet ** @ param string $ action socket send action: REGISTER_DEVICE, SENDCONFIG_DEVICE, GETDEVICE_INFORMATION, LOGOUT_DEVICE * @ param string $ ip address ** @ return bytes return socket data */public function SendPackage ($ action = null, $ ip = null, $ lengthtype = null, $ length = null) {$ TCPv4 = new \ X \ Protocol \ TCPv4 ($ ip, $ this-> agentPort ); $ TCPv4-> SetSendTimeout (5); $ TCPv4-> SetRecvTimeout (30); switch ($ action) {case 'Reg ISTER_DEVICE ': $ this-> DeviceRegister (); break; case 'sendconfig _ device': break; case 'getdevice _ information': $ this-> DeviceInformation (); break; case 'logout _ device': $ this-> DeviceLogout (); break;} $ status = $ TCPv4-> Send ($ this-> package); $ result = ''; if (0 ===$ lengthtype) // fixed length {$ TCPv4-> Recv ($ result, $ length );} else {$ TCPv4-> RecvForDontKnowLength ($ result);} return $ result;} public function Regist ErDevice ($ ip = null) {/** Action: registration behavior: 1: Check whether the device is registered with this Server; 2: register this device with this Server; 3: the device is forcibly registered to this Server regardless of whether the device has been registered with another Server. Result: 0: The device is successfully registered with this Server; 1: registration failed; 2: The device has not been registered; 3: The device has been registered with another Server; 4: Internal error: the specified device ID is different from the existing device ID. **/$ REG_TCP = new \ X \ Protocol \ TCPv4 ($ ip, $ this-> agentPort); $ REG_TCP-> SetSendTimeout (5 ); $ REG_TCP-> SetRecvTimeout (30); $ this-> DeviceRegister (); $ status = $ REG_TCP-> Send ($ this-> package); $ result = ''; $ REG_TCP-> Recv ($ result, 12); $ SERVER_SOCKET_DATA = unpack ('N', substr ($ result, 8, 4); return $ SERVER_SOCKET_DATA [1];}

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.