当前位置: 首页 > 文档资料 > WorkerMan 3.x 手册 >

AsyncTcpConnection类 - connect

优质
小牛编辑
127浏览
2023-12-01
  1. void AsyncTcpConnection::connect()

执行异步连接操作。此方法会立刻返回。

注意:如果需要设置异步连接的onError回调,则应该在connect执行之前设置,否则onError回调可能无法被触发,例如下面的例子onError回调可能无法触发,无法捕获异步连接失败事件。

  1. $connection = new AsyncTcpConnection('tcp://baidu.com:81');
  2. // 执行连接的时候还没设置onError回调
  3. $connection->connect();
  4. $connection->onError = function($connection, $err_code, $err_msg)
  5. {
  6. echo "$err_code, $err_msg";
  7. };

参数

无参数

返回值

无返回值

示例 Mysql代理

  1. use WorkermanWorker;
  2. use WorkermanConnectionAsyncTcpConnection;
  3. require_once __DIR__ . '/Workerman/Autoloader.php';
  4. // 真实的mysql地址,假设这里是本机3306端口
  5. $REAL_MYSQL_ADDRESS = 'tcp://127.0.0.1:3306';
  6. // 代理监听本地4406端口
  7. $proxy = new Worker('tcp://0.0.0.0:4406');
  8. $proxy->onConnect = function($connection)
  9. {
  10. global $REAL_MYSQL_ADDRESS;
  11. // 异步建立一个到实际mysql服务器的连接
  12. $connection_to_mysql = new AsyncTcpConnection($REAL_MYSQL_ADDRESS);
  13. // mysql连接发来数据时,转发给对应客户端的连接
  14. $connection_to_mysql->onMessage = function($connection_to_mysql, $buffer)use($connection)
  15. {
  16. $connection->send($buffer);
  17. };
  18. // mysql连接关闭时,关闭对应的代理到客户端的连接
  19. $connection_to_mysql->onClose = function($connection_to_mysql)use($connection)
  20. {
  21. $connection->close();
  22. };
  23. // mysql连接上发生错误时,关闭对应的代理到客户端的连接
  24. $connection_to_mysql->onError = function($connection_to_mysql)use($connection)
  25. {
  26. $connection->close();
  27. };
  28. // 执行异步连接
  29. $connection_to_mysql->connect();
  30. // 客户端发来数据时,转发给对应的mysql连接
  31. $connection->onMessage = function($connection, $buffer)use($connection_to_mysql)
  32. {
  33. $connection_to_mysql->send($buffer);
  34. };
  35. // 客户端连接断开时,断开对应的mysql连接
  36. $connection->onClose = function($connection)use($connection_to_mysql)
  37. {
  38. $connection_to_mysql->close();
  39. };
  40. // 客户端连接发生错误时,断开对应的mysql连接
  41. $connection->onError = function($connection)use($connection_to_mysql)
  42. {
  43. $connection_to_mysql->close();
  44. };
  45. };
  46. // 运行worker
  47. Worker::runAll();

测试

  1. mysql -uroot -P4406 -h127.0.0.1 -p
  2. Welcome to the MySQL monitor. Commands end with ; or g.
  3. Your MySQL connection id is 25004
  4. Server version: 5.5.31-1~dotdeb.0 (Debian)
  5. Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  6. Oracle is a registered trademark of Oracle Corporation and/or its
  7. affiliates. Other names may be trademarks of their respective
  8. owners.
  9. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
  10. mysql>