php 做 websocket 客户端
时间: 2023-07-20 18:29:10 浏览: 184
php实现的websocket客户端
4星 · 用户满意度95%
要在 PHP 中使用 WebSocket 客户端,可以使用 Ratchet 库。以下是一个简单的示例:
1. 首先,使用 Composer 安装 Ratchet:
```
composer require cboden/ratchet
```
2. 创建一个 WebSocket 客户端 PHP 文件,例如 client.php:
```php
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Client\WebSocket;
$loop = React\EventLoop\Factory::create();
$webSocket = new WebSocket('ws://localhost:8080');
$webSocket->on('open', function ($connection) {
echo "Connected to server\n";
$connection->send('Hello, server!');
});
$webSocket->on('message', function ($message) {
echo "Received message: {$message}\n";
});
$webSocket->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$webSocket->on('error', function ($error) {
echo "Error occurred: {$error}\n";
});
$loop->run();
```
3. 运行这个脚本,它将连接到 WebSocket 服务器并发送一条消息。在终端中运行:
```
php client.php
```
如果一切正常,你应该看到以下输出:
```
Connected to server
Received message: Hello, client!
```
这是服务器发送给客户端的响应。
阅读全文