最簡單的是使用JS編寫:
``` js
socket = new WebSocket('ws://192.168.1.107:9501/');
socket.onopen = function(evt) {
// 發送一個初始化消息
socket.send('I am the client and I\'m listening!');
};
// 監聽消息
socket.onmessage = function(event) {
console.log('Client received a message', event);
};
// 監聽Socket的關閉
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
socket.onerror = function(evt) {
console.log('Client onerror',event);
};
```
Swoole里沒有直接提供swoole_websocket客戶端,不過通過引入[WebSocketClient.php](https://github.com/52fhy/swoole_demo/blob/master/WebSocketClient.php)文件可以實現:
```
<?php
require_once __DIR__ . '/WebSocketClient.php';
$client = new WebSocketClient('192.168.1.107', 9501);
if (!$client->connect())
{
echo "connect failed \n";
return false;
}
$send_data = "I am client.\n";
if (!$client->send($send_data))
{
echo $send_data. " send failed \n";
return false;
}
echo "send succ \n";
return true;
```
上面代碼實現的是一個同步的swoole_websocket客戶端。發送完消息會自動關閉,可以用來與php-fpm應用協作:將耗時任務使用客戶端發送到swoole_websocket_server。