<?php
//异步tcp客户端
$client=new swoole_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC);
//注册连接成功回调
$client->on("connect",function($cli){
$cli->send("how are you\n");
});
$client->on("receive",function($cli,$data){
echo "数据:$data\n";
});
//注册连接失败
$client->on("error",function($cli){
echo "失败\n";
});
$client->on("close",function($cli){
echo "关闭连接\n";
});
//发起链接
$client->connect('127.0.0.1', 9501, -1);
exit;
//客户端
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{
exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->send("hello world1\n");
echo $client->recv();
$client->send("hello world2\n");
echo $client->recv();
$client->close();
服务端如下:
$serv=new swoole_server('127.0.0.1',9501);
$serv->set(array('task_worker_num'=>4));
$serv->on("receive",function($serv,$fd,$from_id,$data){
$serv->send($fd,"Server:".$data);
$task_id=$serv->task($data);
echo "异步id{$task_id}\n";
});
$serv->on("task",function($serv,$task_id,$from_id,$data){
echo "执行异步id为$task_id\n";
$serv->finish("{$data}->ok");
});
$serv->on("finish",function($serv,$task_id,$data){
echo "完成$task_id\n";
});
$serv->start();exit;
网友评论