Error showing in console : WebSocket connection to
'ws://localhost/socket/php-socket.php/wss' failed: Error during
WebSocket handshake: Unexpected response code: 200
PHP Code :
$newSocket = socket_accept($socketResource);
$clientSocketArray[] = $newSocket;
$header = socket_read($newSocket, 1024);
$chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);
enter code here
Handshake function :
function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
$headers = array();
$lines = preg_split("/\r\n/", $received_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$buffer = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host_name\r\n" .
"WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_socket_resource,$buffer,strlen($buffer));
}
Javascript Code :
var websocket = new WebSocket("ws://localhost/socket/php-socket.php");
websocket.onopen = function(event) {
showMessage("<div class='chat-connection-ack'>Connection is established!</div>");
}
Related
I connect to the Minecraft server via tcp, how do I use a proxy server
I know how to use a proxy for HTTP requests, but I don’t really understand how to do it for TCP
$data = "\x00";
$data .= makeVarInt($proto);
$data .= pack('c', strlen($ip)) . $ip;
$data .= pack('n', $port);
$data .= "\x02";
$handshake = pack('c', strlen($data)) . $data;
$nick = generateRandomString(5)."_RAGE_". generateRandomString(5);
//Create TCP socket
$socket = #stream_socket_client("tcp://$ip:$port", $errno, $errstr, 10);
//Check for errors
if ($errno > 0) {
echo "ERROR: " . $errstr . PHP_EOL;
continue;
}
//Send login handshake packet
fwrite($socket, $handshake);
//Make login start packet
$data = "\x00";
$data .= pack('c', strlen($nick)) . $nick;
$data = pack('c', strlen($data)) . $data;
//Send login start packet
fwrite($socket, $data);
The server says: Undefined index Sec-WebSocket-Key during handshake process when I access the site from mobile. From the same pc (localhost) its ok
function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
$headers = array();
$lines = preg_split("/\r\n/", $received_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$buffer = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host_name\r\n" .
"WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_socket_resource,$buffer,strlen($buffer));
}
You need to replace $hostname "localhost" with the ip address assigned to your computer.
You can visit https://www.tp-link.com/us/support/faq/838/ for finding out ip address of your host computer.
I use socket.io for socket app in my client side. For the server I use socket library of PHP.
After the handsake, the connection was closed and generated a warning
failed: WebSocket is closed before the connection is established.
socket_getsockname($socket_server, $addr, $port);
while($socket = socket_accept($socket_server)) {
$handshake = false;
if(!$socket){
print "error \n";
}
socket_getpeername($socket, $raddr, $rport);
$msg = "Welcome aboard !";
$length = strlen($msg);
print socket_read ( $socket , 255 )."\n";
$error = socket_last_error($socket);
$error_message = socket_strerror($error);
if(!$handshake){
$bytes = socket_recv($socket,$buffer,2048,0);
list($resource,$host,$origin,$key,$key1,$key2,$l8b) = getheaders($buffer);
$accept = base64_encode(SHA1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
$upgrade = "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" .
"Upgrade: WebSocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Origin: " . $origin . "\r\n" .
"Sec-WebSocket-Location: ws://" . $host . $resource . "\r\n" .
"Sec-WebSocket-Accept: " . $accept . "\r\n\r\n";
if(socket_write($socket,$upgrade.chr(0),strlen($upgrade.chr(0)))) {
$handshake = true;
}
}
else{
if(socket_write ( $socket , $msg,$length)){
print "Mesg envoyee \n";
}
}
do{
$read = socket_read($socket, 1080);
print $read."\n";
if(socket_write ( $socket , $msg,$length)){
print "Mesg envoyee \n";
}
} while ($read != '');
in my server side in PHP
in my client :
var socket = io('http://localhost:4454',{
agent: false,
transports: ['websocket']
});
console.log(socket);
socket.on('connect', () => {
socket.send('hi');
console.log(socket);
});
socket.emit('foo');
socket.on('message', (data) => {
console.log(data);
console.log(socket);
});
socket.on('data', (data) => {
console.log(data);
});
socket.on('error', (error) => {
console.log(error);
});
//blocage des reconnection si erreurs
var attemp = 5;
socket.on('reconnecting', (attemp) => {
console.log("I'm sad :(");
//socket.close();
});
I don't find any solution for this issue.
I don't understand why in localhost stream was automatically close.
Server side looked fine, in this time...
i am working to send sms with ozeki NG and PHP, and i can send SMS from localhost but when i upload it on cpanel it says "fsockopen(): unable to connect to 197.XXX.XXX.XX:9501 (Connection timed out)"
IS THEIR ANY ONE WHO COULD HELP ME...thanks in advance...
$ozeki_user = "xxxx";
$ozeki_password = "xxxx";
$ozeki_url = "http://197.xxx.xxx.xxx:9501/api?";
function httpRequest($url){
$pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
preg_match($pattern,$url,$args);
$in = "";
$fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
if (!$fp) {
return("$errstr ($errno)");
} else {
$out = "GET /$args[3] HTTP/1.1\r\n";
$out .= "Host: $args[1]:$args[2]\r\n";
$out .= "User-agent: Ozeki PHP client\r\n";
$out .= "Accept: */*\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
$in.=fgets($fp, 128);
}
}
fclose($fp);
return($in);
}
function ozekiSend($phone, $msg, $debug=true){
global $ozeki_user,$ozeki_password,$ozeki_url;
$url = 'username='.$ozeki_user;
$url.= '&password='.$ozeki_password;
$url.= '&action=sendmessage';
$url.= '&messagetype=SMS:TEXT:UCS2';
$url.= '&recipient='.urlencode($phone);
$url.= '&messagedata='.urlencode($msg);
//$url.= '&messagedata='.urlencode($msg);
$urltouse = $ozeki_url.$url;
if ($debug) { echo "Request: <br>$urltouse<br><br>"; }
//Open the URL to send the message
$response = httpRequest($urltouse);
if ($debug) {
echo "Response: <br><pre>".
str_replace(array("<",">"),array("<",">"),$response).
"</pre><br>"; }
return($response);
}
$phonenum = $_POST['recipient'];
$message = $_POST['message'];
$debug = true;
ozekiSend($phonenum,$message,$debug);
?>
I have a websocket server running by PHP using socket_create().
I am using following code :
function customError($errno, $errstr, $errfile, $errline) {
$theerror= "Error [$errno] in $errfile on line $errline : $errstr ";
$errorlogfile = fopen(date("d_m_y")."socket.log", "a");
fwrite($errorlogfile, PHP_EOL.date("h:i:s").' - '.$theerror);
fclose($errorlogfile);
}
set_error_handler("customError");
function wmlog($log){
$f=fopen(date("d_m_y").'socket.log','a');
fwrite($f, $log." \r\n ");
fclose($f);
}
$wmdir=dirname(__FILE__);
$host = 'srvdb';
$port = $argv[1];
/* $ccode=$argv[4];
$uid=$argv[3] ;
$cid=$argv[4]; */
$null = NULL; //host
if(!$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP){
wmlog("ERROR creating socket") ;
}else{
wmlog("socket created") ;
}
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);//reuseable port
socket_bind($socket, $host, $port);//bind socket to specified host
socket_listen($socket);//listen to port
$clients = array($socket);//create & add listning socket to the list
include_once($wmdir.'/intochat_f.php');
//include_once($wmdir.'/include1.php');
wmlog("included") ;
//start endless loop, so that our script doesn't stop
while (true) {//manage multipal connections
$changed = $clients;
socket_select($changed, $null, $null, 0, 10);//returns the socket resources in $changed array
///////// AD NEW SOCKET ///////
// $a_pv - passed values ()
if (in_array($socket, $changed)) {//check for new socket
$socket_new = socket_accept($socket); //accpet new socket
$header = socket_read($socket_new, 1024); //read data sent by the socket
$a_h=explode(PHP_EOL, $header);
$s_get=$a_h[0];
unset($a_h[0]) ;
$a_header=array();
foreach($a_h as $v){
$nk=strtok($v, ":");
$nv=substr($v, (strrpos($v, ':') ?: -1) +1);
$a_header[$nk]=$nv;
}
$a_pv=explode('_', $s_get);
$a_pv[0] = $a_header['Sec-WebSocket-Protocol'];
$pid=$a_pv[1];
$clients[$pid] = $socket_new; //add socket to client array
wmlog('HEADER: '. " \r\n ". $header. " \r\n EOF HEADER ");
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
wmlog((socket_getpeername($socket_new, $ip))." ip: ".$ip. "\r\n") ; //get ip address of connected socket
//$response = mask(json_encode(array('act2'=>30))); //prepare json data
//send_message($response, $pid); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//loop through all connected sockets
foreach ($changed as $socketid => $changed_socket) {
//check for any incomming data and do smth with it
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = unmask($buf);
$msg = json_decode($received_text);//unmask data AND json decode
// PUT MESSAGE TO DB ////
/// SEND MESSAGE TO OTHERS (priv or everybody )///
if(isset($msg->to) && $msg->to >0 ){
$scopeid=$msg->to;
}else{
$scopeid=0;
}
//$a_response=$msg.
//prepare data to be sent to client
$response_text = mask(json_encode(array('val1'=>$msg->val1, 'val2'=>$msg->val2, 'from'=>$socketid )));
send_message($response_text, $scopeid); //send data
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('val1'=>'somebody left', 'val2'=>' left user')));
send_message($response);
}
}
}
socket_close($socket);
function send_message($msg, $id=0){
global $clients;
if($id==0){ // send message to everybody
foreach($clients as $changed_socket){
#socket_write($changed_socket,$msg,strlen($msg));
}
}else{ // send message to selected socket
#socket_write($clients[$id],$msg,strlen($msg));
}
return true;
}
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}else{
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
function mask($text){
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
function perform_handshaking($receved_header,$client_conn, $host, $port) {
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach($lines as $line) {
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)){
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
If I use connect to it from browser (using javascript new WebSocket(wsUri); ) - it works fine, but when I try to connect to it from PHP script using fsockopen(), data after unmasking looks gibberish but like valid JSON before unmasking.
And the question is - why is unmasking not working when sending data via PHP fsockopen / how to make it work?
I found by google in one forum this (tools.ietf.org/html/rfc6455):
A server MUST NOT mask any frames that it sends to the client.
A client MUST close a connection if it detects a masked
frame.