error "not a valid Socket resource" implementing the phpwebsocket library - phpwebsocket

I'm trying to work with the phpwebsocket library at http://code.google.com/p/phpwebsocket/
I'm using the version r8 of the server.php file. For testing I just tried with the client.html file, also provided by the website.
When the server is started I get this:
Server Started : 2011-08-29 22:11:23
Master socket : Resource id #4
Listening on : www.midomain.com port 12345
But when I load the client.html file in the browser, the server shows the following errors:
Notice: Undefined variable: key1 in /home/mink500/public_html/test/server.php on line 143
Notice: Undefined variable: key2 in /home/mink500/public_html/test/server.php on line 143
Warning: socket_select(): 5 is not a valid Socket resource in /home/mink500/public_html/test/server.php on line 15
There are two variables that are not defined, and the function socket_select() returns the error "5 is not a valid Socket resource"
In the browser I get the "Disconnected" message as soon as the file is loaded.
I tried to make the server work locally using XAMPP (Apache and PHP) but I got the same errors. I also tried to change ports and follow the instructions in this issue:
http://code.google.com/p/phpwebsocket/issues/detail?id=33
But I still get the error "5 is not a valid Socket resource"
I remember that refreshing the page several times I got it running a few months ago, but now it's impossible. Besides, I need it to work all the time, not just after I refresh the page like 20 times.
I also tried with the websocket.class.php file, but this time I get an error on the client side. The browser now returns "Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing".
So, I can't make it work with old or new files, with remote or local server, with magic or a ouija board!
Any idea?
Thanks

Starting with the newest phpwebsocket client.html and server.php files I replaced both the getheaders() and dohandshake() functions with the code below works for me in newest Chrome. However it currently does not write to the browser nor stay alive after one uer comment in the chat box.
function dohandshake($user, $buffer) {
$key = null;
console("\nRequesting handshake...");
console($buffer);
console("Handshaking...");
preg_match("#Sec-WebSocket-Key: (.*?)\r\n#", $buffer, $match) && $key = $match[1];
$key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$key = sha1($key);
$key = pack('H*', $key);
$key = base64_encode($key);
$upgrade =
"HTTP/1.1 101 Switching Protocols\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Accept: {$key}\r\n\r\n";
socket_write($user->socket, $upgrade . chr(0), strlen($upgrade . chr(0)));
$user->handshake = true;
console($upgrade);
console("Done handshaking...");
return true;
}
function getheaders($header) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach ($fields as $field) {
if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if (isset($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
if (preg_match("/GET (.*) HTTP/", $header, $match)) {
$retVal['GET'] = $match[1];
}
return $retVal;
}

Related

check website url status using powershell version 2.0

I need to check if URL is working properly or not using "PowerShell Version 2.0"
I found this script over internet, but it is not wokring fine for wrong URL's. It should go in else loop for wrong URL's as well as print website code. And I am not able to pass credentials in this script.
e.g. for www.google.com(correct URL) status code should be 200but
for www.gfjgugy79rt9(Wrong URL) status code should be something like 404
script I found over internet for powershell version 2.0:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
$HTTP_Response.Close()
In PowerShell higher than 2.0 you should use try ... catch ... finally because this code fire exception when the URI is no conform or when the adress part is not solvable by the DNS :
try {
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
}
catch {
Write-Verbose $_.ScriptStackTrace
Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
}
finally {
# Finally, we clean up the http request by closing it.
$HTTP_Response.Close()
}
In PowShell 2.0 you just have to put a Trap code at the beginnig of the scope (function, script) where you want to catch these exception :
trap
{
Write-Verbose $_.ScriptStackTrace
Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
Write-Verbose ([datetime]::Now)
return
}

Issues using ratchetphp/Pawl websocket client

My question is specific to using slack rtm on ratchetphp/Pawl. I have below code which connects fine but dies eventually.
<?php
require_once "response.php";
//first make authenticated call to rtm.start
use \Curl\Curl;
$curl = new Curl();
$rtmStartUrl = "https://slack.com/api/rtm.start?token=xx-xx-xx-xx-xx&pretty=1";
$curl->get($rtmStartUrl);
$wsUrl = $curl->response->url;
$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);
$connector($wsUrl)
->then(function(Ratchet\Client\WebSocket $conn) {
$conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "Received: {$msg}\n";
// $conn->close();
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
Upon running, the output is:
root#ip-172-31-45-75:/var/www/html/slack# php pawl.php
Received: {"type":"hello"}
Received: {"type":"reconnect_url","url":"wss://mpmulti-qpau.slack-msgs.com/websocket/jDkgDysXfZspRj10zqdcrshHK6PhPLItYx2HEkdXy47RPCAJwKgI_NLq0bhS4uMjIT7iRtOoCDUJffcxcr7YdiqMbITUZYqnTmT39Et5a8JeuPLFfCUUzan4MCz34p0jcfAKaQW9G9HpIWrYH4CTqyICZuhgWHnzo8K7dO2zXFc="}
Received: {}
Connection closed (1006 - Underlying connection closed)
root#ip-172-31-45-75:/var/www/html/slack#
The websocket is part of slack rtm api (https://api.slack.com/rtm). It seems like when reading on empty websocket, the connection is closed. I think it might be like we listen to slack events (https://api.slack.com/events) sent over websocket for working to avoid disconnect.
Currently, this does not work because of disconnection error.
Hello World! is not a valid message for this API, so Slack is closing the connection when it receives that message. Try sending something valid (or nothing at all).

Tcl script breaks out of foreach loop

I have a tcl script to log into devices and print SUCCESS. This is the script:
The file: (the first IP is valid, and can be logged into, the next 3 are fake).
192.38.133.145
178.18.34.48
183.24.56.3
145.234.67.145
The script:
#!/bin/expect
package require Expect
set file [open "hosts" r]
set f_data [read $file]
set data [split $f_data "\n"]
foreach host $data {
set timeout 8
if {$host > 0} {
## GETS THE HOST IP##
set host_ip $host
##LOGS INTO THE DEVICE##
spawn ssh test#$host_ip
expect {
"password:" {
puts "SUCCESS"
} timeout {
puts "Could not connect to host: ${host_ip}"
#break
}
}
send "password\r"
expect ">"
send "en\r"
}
}
If I do not include the break, I get the message could not connect to host, but instead of looping to the next host, it sends "en\r".
when I do include the break, it gives the message that it cannot reach the host (the second IP, which is expected) and the script ends there (it does not process the 3rd IP). How do I cannot seem to get it to process the 3rd and 4th IPs.
I used the method suggested by potrzebie in this thread: TCL: loops How to get out of inner most loop to outside?
and still cannot get it to work
break should work. The expect man page has this to say in the documentation for the expect command:
Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way.
I'd write your loop like this:
foreach host $data {
# very basic data validation: an ipv4 address contains some dots
if {[string match {*.*.*.*} $host]} {
spawn ssh test#$host
expect {
"password:" {
puts "SUCCESS"
send "password\r"
exp_continue
}
timeout {
puts "Could not connect to host: $host"
continue
}
">" {
# I see a prompt. Fall out of this "expect loop"
}
}
send "en\r"
expect ">"
# do something to close the connection
send "exit\r"
expect eof
}
}

Stuck messages in ZeroMQ

I'm having a strange problem with ZeroMQ, in which some messages get stuck, and just get unstuck when new messages arrive. It's like the new messages push the stuck messages on the door (terrible comparison, i know).
My code is quite simple:
rep.php
$context = new ZMQContext;
$receiver = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver->connect("tcp://localhost:8022");
$receiver2 = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver2->connect("tcp://localhost:8024");
for (;;) {
echo $receiver->recv() . PHP_EOL;
echo $receiver2->recv() . PHP_EOL;
}
cnt.php and cnt2.php (same code, different ports)
$context = new ZMQContext;
$work = new ZMQSocket($context, ZMQ::SOCKET_PUSH);
$work->bind('tcp://*:8022');
$work->send('Hello World');
cnt.php sends to 8022 and cnt2.php to 8024. They get executed from time to time and send messages to rep.php. However, some messages get stuck. If i sent 4 messages from cnt.php, nothing is received, but when i send 1 from cnt2.php, i get 5 messages at once. Any ideas?
I am no PHP expert here but guessing the syntax and functionality. Please correct me if I am wrong
echo $receiver->recv() . ' - ' . $receiver2->recv();
recv() should be a blocking call.
$receiver->recv() blocks until some message is received.
But echo does not echo the message immediately
You are again blocked on $receiver2->recv()
Only when you send message from the other file does echo work because it is waiting on $receiver2->recv()
Since you want to process the socket recv() independently, you should use polling or event based asynchronous I/O.
[Attempted solution]
$poll = new ZMQPoll();
$poll->add($receiver, ZMQ::POLL_IN);
$poll->add($receiver2, ZMQ::POLL_IN);
$readable = $writeable = array();
while(true) {
$events = $poll->poll($readable, $writeable);
foreach($readable as $socket) {
$message = $socket->recv();
echo $message, PHP_EOL;
}
}
Adapted from : http://zguide.zeromq.org/php:rrbroker

failed to upgrade a token

I was testing Zend Gdata 1.10.1 in my localhost.
I downloaded Zend Gdate from this link:
http://framework.zend.com/download/webservices
Inside the Zend Gdata zip file, there was a folder called demos.
I extracted it and used the YouTudeVideoApp to upload a sample video to Youtube.
But every time after I logged into Youtube, before it redirected me to my localhost,
I received a warning message like this warning message:
localhost: This website is registered
with Google to make authorization
requests, but has not been configured
to send requests securely. We
recommend that you continue the
process only if you trust the
following destination:
localhost:8080/youtube/operations.php
So I googled on how to resolve the problem of getting this warning message when
I saw some people suggesed changing the value of $secure to True in operation.php.
Here is the script mentioned:
function generateAuthSubRequestLink($nextUrl = null)
{
$scope = 'http://gdata.youtube.com';
$secure = true;
$session = true;
if (!$nextUrl) {
generateUrlInformation();
$nextUrl = $_SESSION['operationsUrl'];
}
$url = Zend_Gdata_AuthSub::getAuthSubTokenUri($nextUrl, $scope, $secure, $session);
echo '<a href="' . $url
. '"><strong>Click here to authenticate with YouTube</strong></a>';
}
After I altered the value of $secure to True,
I found that the warning message changed to this:
localhost: Registered, secure. This
website is registered with Google to
make authorization requests
The new warning message is somehow shorter and looks better than the previous warning message.
But once I pressed the Allow Access button, it turned out to be this:
ERROR - Token upgrade for
CI3M6_Q3EOGkxoL-_____wEYjffToQQ failed
: Token upgrade failed. Reason:
Invalid AuthSub header. Error 401
ERROR - Unknown search type - ''
I don't know why this happened.
Could you help me solve the problem please?
edit your php.ini file and enable the openssl extensions
extension=php_openssl.dll
restart the httpd or IIS server

Resources