最简单的是使用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。