Thursday, June 28, 2012

php simple websocket client


hi

i experiencing websocket connections using php,nodejs for server side and using jquery for client side, soon i hope to publish my simple experiments for others newbies. for now i with this simple php script that i used to debug my apps it's a simple client that send data to nodejs http.server and stamp
the response received i hope that for someone it will be useful

Kevin Pham

the code:

<?

 $host = 'localhost';  //where is the websocket server
 $port = 9000;
 $local = "http://localhost/";  //url where this script run
 $data = 'hello world!';  //data to be send

 $head = "GET / HTTP/1.1"."\r\n".
   "Upgrade: WebSocket"."\r\n".
   "Connection: Upgrade"."\r\n".
   "Origin: $local"."\r\n".
   "Host: $host"."\r\n".
   "Content-Length: ".strlen($data)."\r\n"."\r\n";
 ////WebSocket handshake
 $sock = fsockopen($host, $port, $errno, $errstr, 2);
 fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
 $headers = fread($sock, 2000);
 fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
 $wsdata = fread($sock, 2000);  //receives the data included in the
websocket package "\x00DATA\xff"
 $retdata = trim($wsdata,"\x00\xff"); //extracts data
 ////WebSocket handshake
 fclose($sock);

 echo $retdata  //data result
?>

No comments:

Post a Comment

Popular Posts