TCP 非同步建立一個到實際mysql伺服器的連線
<?php
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
require_once './Workerman/Autoloader.php';
// 建立一個Worker監聽2345埠,使用http協議通訊
$tcp_worker = new Worker("tcp://0.0.0.0:2345");
// 啟動4個程序對外提供服務
$tcp_worker->count = 4;
$tcp_worker->onConnect = function ($connection) {
echo 'new connection '.$connection->getRemoteIp().PHP_EOL;
// 非同步建立一個到實際mysql伺服器的連線
$connection_to_mysql = new AsyncTcpConnection('tcp://172.17.0.3:3306');
// mysql連線發來資料時,轉發給對應客戶端的連線
$connection_to_mysql->onMessage = function ($connection_to_mysql, $data) use ($connection) {
$connection->send($data);
};
// mysql連線關閉時,關閉對應的代理到客戶端的連線
$connection_to_mysql->onClose = function($connection_to_mysql) use ($connection) {
$connection->close();
};
// 執行非同步連線
$connection_to_mysql->connect();
// 客戶端發來資料時,轉發給對應的mysql連線
$connection->onMessage = function($connection, $data) use ($connection_to_mysql) {
$connection_to_mysql->send($data);
};
// 客戶端連線斷開時,斷開對應的mysql連線
$connection->onClose = function($connection) use ($connection_to_mysql) {
$connection_to_mysql->close();
};
};
// 接收到瀏覽器傳送的資料時回覆hello world給瀏覽器
$tcp_worker->onMessage = function($connection, $data)
{
// 向瀏覽器傳送hello world
// $connection->send('hello world');
// $connection->close();
echo $data;
};
// 執行worker
Worker::runAll();