<?php
$server = new Swoole\Server('0.0.0.0', 39055);
$socket = null;
//监听连接进入事件
$server->on('Connect', function ($server, $fd) {
echo "Client: Connect.\n";
// 作为客户端连接mysql服务
global $socket;
$socket = new Co\Socket(AF_INET, SOCK_STREAM, 0);
// 利用协程,不在当前进程阻塞
go(function () use ($socket, $server, $fd) {
// 连接mysql数据库
$retval = $socket->connect('127.0.0.1', 3306);
while ($retval)
{
// 接收mysql响应
$data = $socket->recv();
if(empty($data)){
break;
}
// 发送给客户端
$server->send($fd,$data);
echo "mysql send===================\n".$data."\n";
}
});
});
//监听数据接收事件
$server->on('Receive', function ($server, $fd, $from_id, $data) {
// 将客户端的数据发送给mysql
global $socket;
$socket->send($data);
echo "client send-----------------\n".$data."\n";
});
//监听连接关闭事件
$server->on('Close', function ($server, $fd) {
echo "Client: Close.\n";
});
//启动服务器
$server->start();
暂无评论