Reputation: 39
i've created a websocket server using Ratchet and a JS client. Whenever the JS client connects to the server, the connection goes idle for 4 minutes before it gives me a handshake timeout. I've tried to disable the firewall, change the port, use another webBrowser, even tried the online tutorial, nothing worked so far. Please Help!
here's the Server code:
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
require __DIR__ . '/vendor/autoload.php';
class RatchetWebSocketServer implements MessageComponentInterface{
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->send($e->getMessage());
}
public function onMessage(ConnectionInterface $from, $msg) {
$from->send("Server returned : ".$msg);
}
public function onOpen(ConnectionInterface $conn) {
}
}
$server = IoServer::factory(new RatchetWebSocketServer(), 8888);
$server->run();
here's the JS client code:
function startServer(){
try{
var socket = new WebSocket("ws://127.0.0.1:80/CharlieTaxi/RatchetWebSocketServer.php");
socket.onopen = function(){
console.log("Socket Status: "+socket.readyState);
//send message to socket server
socket.send("Hello from Alfred to Server");
socket.close();
};
socket.onmessage = function(msg){
console.log(msg.data);
// socket.close();
};
socket.onclose = function(){
console.log('connection is closed!');
};
}
catch(e){
console.log(e);
}
}
Here's the request header (Chrome Browser) :
Provisional headers are shown // this line is in bold with a yellow warning sign on the left
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8-
Cache-Control:no-cache
Connection:Upgrade
Cookie:PHPSESSID=pgo5ma6o5mlh6k9mtfcad4k6d4
Host:127.0.0.1
Origin:http://127.0.0.1
Pragma:no-cache
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
Sec-WebSocket-Key:sVGKPRvSUghm1xdCgBQCsA==
Sec-WebSocket-Version:13
Upgrade:websocket
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36
this is the console output after it gives me the timeout:
WebSocket connection to 'ws://127.0.0.1/CharlieTaxi/RatchetWebSocketServer.php' failed: WebSocket opening handshake timed out
here's the composer.json file content :
{
"require": {
"cboden/ratchet": "0.3.*"
}
}
Upvotes: 1
Views: 7512
Reputation: 2719
You are connecting to your websocket incorrectly. A websocket is not just a file you connect to, it has to be its own process. In your command line run, navigate to the directory RatchetWebSocketServer.php
is stored in and run
php RatchetWebSocketServer.php
Then in javascript connect to 127.0.0.1:8888
and the WebSocket should work.
Don't forget that every time you change your WebSocket code you need to stop that php xx
command and start it again.
Upvotes: 3