常见问题 - 作为ws/wss客户端
优质
小牛编辑
126浏览
2023-12-01
有时候需要让workerman作为客户端以ws/wss协议去连接某个服务端,并与之交互。
以下是示例。
1、workerman作为ws客户端
<?php
use WorkermanWorker;
use WorkermanConnectionAsyncTcpConnection;
require_once __DIR__ . '/../Workerman/Autoloader.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker){
$con = new AsyncTcpConnection('ws://echo.websocket.org:80');
$con->onConnect = function($con) {
$con->send('hello');
};
$con->onMessage = function($con, $data) {
echo $data;
};
$con->connect();
};
Worker::runAll();
2、workerman作为wss(ws+ssl)客户端
<?php
use WorkermanWorker;
use WorkermanConnectionAsyncTcpConnection;
require_once __DIR__ . '/../Workerman/Autoloader.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker){
// ssl需要访问443端口
$con = new AsyncTcpConnection('ws://echo.websocket.org:443');
// 设置以ssl加密方式访问,使之成为wss
$con->transport = 'ssl';
$con->onConnect = function($con) {
$con->send('hello');
};
$con->onMessage = function($con, $data) {
echo $data;
};
$con->connect();
};
Worker::runAll();
3、workerman作为wss(ws+ssl)客户端(需要本地ssl证书)
<?php
use WorkermanWorker;
use WorkermanConnectionAsyncTcpConnection;
require_once __DIR__ . '/../Workerman/Autoloader.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker){
// 设置访问对方主机的本地ip及端口以及ssl证书
$context_option = array(
// ssl选项,参考http://php.net/manual/zh/context.ssl.php
'ssl' => array(
// 本地证书路径。 必须是 PEM 格式,并且包含本地的证书及私钥。
'local_cert' => '/your/path/to/pemfile',
// local_cert 文件的密码。
'passphrase' => 'your_pem_passphrase',
// 是否允许自签名证书。
'allow_self_signed' => true,
// 是否需要验证 SSL 证书。
'verify_peer' => false
)
);
// ssl需要访问443端口
$con = new AsyncTcpConnection('ws://echo.websocket.org:443', $context_option);
// 设置以ssl加密方式访问,使之成为wss
$con->transport = 'ssl';
$con->onConnect = function($con) {
$con->send('hello');
};
$con->onMessage = function($con, $data) {
echo $data;
};
$con->connect();
};
Worker::runAll();