我在后端运行Ratchet WebSocketServer,一切正常。
disableVersion(0); $server = \Ratchet\Server\IoServer::factory( new HttpServer( $wsServer ), 8080 ); $server->run();
但是我想使用简单的php脚本连接到websocket,以将消息发送到服务器。
$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);
但是我收到的错误是。
error:32744:Unable to find the socket transport "ws" - did you forget to enable it when you configured PHP?
然后,当我更改主机并且不使用ws://时,它说。
error:111:Connection refused
有谁知道如何将数据从纯PHP文件发送到正在运行的Ratchet WebSocket服务器?
我已经与Ratchet一起尝试了这个项目,它可以完美地用作PHP客户端:
https://github.com/Textalk/websocket-php
安装方式:
composer require textalk/websocket 1.0.*
还有一个用法示例:
send("Hello from PHP"); echo $client->receive() . "\n"; // Should output 'Hello from PHP'
我进行了测试,如果您使用wss://(用于远程websocket),它也可以与SSL一起使用。