Connecting to a ratchet websocket server using PHP

DB93 picture DB93 · Jul 20, 2016 · Viewed 8.5k times · Source

I am running a Ratchet WebSocketServer in my backend this is all working fine.

<?php

require '../vendor/autoload.php';

use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;

$wsServer = new WsServer(new Chat());
$wsServer->disableVersion(0);

$server = \Ratchet\Server\IoServer::factory(
    new HttpServer(
        $wsServer
    ),
    8080
);

$server->run();

But I want to connect to the websocket using a plain php script to send a message to the server.

$host = 'ws://localhost';  //where is the websocket server
$port = 8080;
$local = "http://example.com";  //url where this script run 
$data = "first message";  //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:$port"."\r\n".
    "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
    "Content-Length: ".strlen($data)."\r\n"."\r\n";

//WebSocket handshake
$sock = fsockopen($host, $port);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);

echo $headers;

fwrite($sock, $data) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);

But the error I receive is.

error:32744:Unable to find the socket transport "ws" - did you forget   to enable it when you configured PHP?

Then when I change the host and don't use the ws:// and it says.

error:111:Connection refused

Does anyone have an idea how to send data to a running Ratchet WebSocket Server from a plain php file?

Answer

RaisinBranCrunch picture RaisinBranCrunch · Mar 25, 2017

I have tried this project alongside Ratchet, and it works perfectly as a PHP client:

https://github.com/Textalk/websocket-php

Install with: composer require textalk/websocket 1.0.*

And a usage example:

<?php

require('vendor/autoload.php');

use WebSocket\Client;

$client = new Client("ws://127.0.0.1:1234");
$client->send("Hello from PHP");

echo $client->receive() . "\n"; // Should output 'Hello from PHP'

I tested, and this also works with SSL if you're using wss:// (for remote websockets).