作为wss客户端

有时候需要让workerman作为客户端以ws/wss协议去连接某个服务端,并与之交互。
以下是示例。

1、workerman作为ws客户端

  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Connection\AsyncTcpConnection;
  4. require_once __DIR__ . '/../Workerman/Autoloader.php';
  5. $worker = new Worker();
  6. $worker->onWorkerStart = function($worker){
  7. $con = new AsyncTcpConnection('ws://echo.websocket.org:80');
  8. $con->onConnect = function($con) {
  9. $con->send('hello');
  10. };
  11. $con->onMessage = function($con, $data) {
  12. echo $data;
  13. };
  14. $con->connect();
  15. };
  16. Worker::runAll();

2、workerman作为wss(ws+ssl)客户端

  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Connection\AsyncTcpConnection;
  4. require_once __DIR__ . '/../Workerman/Autoloader.php';
  5. $worker = new Worker();
  6. $worker->onWorkerStart = function($worker){
  7. // ssl需要访问443端口
  8. $con = new AsyncTcpConnection('ws://echo.websocket.org:443');
  9. // 设置以ssl加密方式访问,使之成为wss
  10. $con->transport = 'ssl';
  11. $con->onConnect = function($con) {
  12. $con->send('hello');
  13. };
  14. $con->onMessage = function($con, $data) {
  15. echo $data;
  16. };
  17. $con->connect();
  18. };
  19. Worker::runAll();

3、workerman作为wss(ws+ssl)客户端(需要本地ssl证书)

  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Connection\AsyncTcpConnection;
  4. require_once __DIR__ . '/../Workerman/Autoloader.php';
  5. $worker = new Worker();
  6. $worker->onWorkerStart = function($worker){
  7. // 设置访问对方主机的本地ip及端口以及ssl证书
  8. $context_option = array(
  9. // ssl选项,参考http://php.net/manual/zh/context.ssl.php
  10. 'ssl' => array(
  11. // 本地证书路径。 必须是 PEM 格式,并且包含本地的证书及私钥。
  12. 'local_cert' => '/your/path/to/pemfile',
  13. // local_cert 文件的密码。
  14. 'passphrase' => 'your_pem_passphrase',
  15. // 是否允许自签名证书。
  16. 'allow_self_signed' => true,
  17. // 是否需要验证 SSL 证书。
  18. 'verify_peer' => false
  19. )
  20. );
  21. // ssl需要访问443端口
  22. $con = new AsyncTcpConnection('ws://echo.websocket.org:443', $context_option);
  23. // 设置以ssl加密方式访问,使之成为wss
  24. $con->transport = 'ssl';
  25. $con->onConnect = function($con) {
  26. $con->send('hello');
  27. };
  28. $con->onMessage = function($con, $data) {
  29. echo $data;
  30. };
  31. $con->connect();
  32. };
  33. Worker::runAll();