connect 方法

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