Connecting to a ratchet websocket server using PHP
Asked Answered
D

1

3

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?

Dispraise answered 20/7, 2016 at 9:24 Comment(0)
T
10

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).

Try answered 25/3, 2017 at 5:30 Comment(4)
@Raisin.can we send byte array using this library through websocket in phpDecanal
The library expects the send() function to be passed a string. If you have your server in PHP (e.g. Ratchet), you could just serialize the byte array on the client and have the server unserialize it. If not all messages received on Ratchet are going to be byte arrays, you might want to prefix those messages like byte_array:a:44:{i:1;i:84; ...etc.Try
ya if i seialize then its send as a string but for me recieving side is only byte array so cant do serialise.Decanal
In my case, I used php composer require textalk/websocket with non-root user to install the library. Moreover I deleted the echo $client->receive() and I used $client->close() instead.Disdainful

© 2022 - 2024 — McMap. All rights reserved.