after server
<?php
class Server
{
private $serv;
public function __construct() {
$this->serv = new swoole_server("0.0.0.0", 9501);
$this->serv->set(array(
'worker_num' => 8,
'daemonize' => false,
'max_request' => 10000,
'dispatch_mode' => 2,
'debug_mode'=> 1,
));
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on('Receive', array($this, 'onReceive'));
$this->serv->on('Close', array($this, 'onClose'));
// bind callback
// $this->serv->on('Timer' , array($this, 'onTimer'));
$this->serv->start();
}
public function onStart( $serv ) {
echo "Start\n";
}
public function onConnect( $serv, $fd, $from_id ) {
echo "Client {$fd} connect\n";
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
echo "Get Message From Client {$fd}:{$data}\n";
$param = array(
'fd' => $fd,
'msg' => $data
);
$str = json_encode( $param );
$serv->after( 1000 , array($this, 'onAfter') , $str );
}
public function onClose( $serv, $fd, $from_id ) {
echo "Client {$fd} close connection\n";
}
public function onAfter( $data ) {
$param = json_decode( $data, true );
$this->serv->send( $param['fd'] , $param['msg']);
}
public function onTimer( $serv, $interval ) {
// Do nothing.
}
}
new Server();
// use src/o2/swoole_async_client to test the server.
?>
after client
<?php
class Client
{
private $client;
public function __construct() {
$this->client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$this->client->on('Connect', array($this, 'onConnect'));
$this->client->on('Receive', array($this, 'onReceive'));
$this->client->on('Close', array($this, 'onClose'));
$this->client->on('Error', array($this, 'onError'));
}
public function connect() {
$fp = $this->client->connect("127.0.0.1", 9501 , 1);
if( !$fp ) {
echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
return;
}
}
public function onReceive( $cli, $data ) {
echo "Get Message From Server: {$data}\n";
}
public function onConnect( $cli) {
fwrite(STDOUT, "Enter Msg1:");
swoole_event_add(STDIN, function($fp){
global $cli;
fwrite(STDOUT, "Enter Msg2:");
$msg = trim(fgets(STDIN));
$cli->send( $msg );
});
}
public function onClose( $cli) {
var_dump($cli);exit;
echo "Client close connection\n";
}
public function onError() {
}
public function send($data) {
$this->client->send( $data );
}
public function isConnected() {
return $this->client->isConnected();
}
}
$cli = new Client();
$cli->connect();
server
client
这个可以用作收到某个消息后 然后执行某些任务
大概这个样子原代码还是参考上一篇之前大神的代码 只是加了一些自己测试