下面貼一個基本的基于swoole的echo服務(wù)器
// Server
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'));
$this->serv->start();
}
public function onStart( $serv ) {
echo "Start\n";
}
public function onConnect( $serv, $fd, $from_id ) {
$serv->send( $fd, "Hello {$fd}!" );
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
echo "Get Message From Client {$fd}:{$data}\n";
}
public function onClose( $serv, $fd, $from_id ) {
echo "Client {$fd} close connection\n";
}
}
// 啟動服務(wù)器
$server = new Server();
從代碼中可以看出,創(chuàng)建一個swoole_server基本分三步: 1. 通過構(gòu)造函數(shù)創(chuàng)建swoole_server對象 2. 調(diào)用set函數(shù)設(shè)置swoole_server的相關(guān)配置選項 3. 調(diào)用on函數(shù)設(shè)置相關(guān)回調(diào)函數(shù) 關(guān)于set配置選項以及on回調(diào)函數(shù)的具體說明,請參考我整理的swoole文檔( 配置選項)
這里只給出簡單介紹。onStart回調(diào)在server運行前被調(diào)用,onConnect在有新客戶端連接過來時被調(diào)用,onReceive函數(shù)在有數(shù)據(jù)發(fā)送到server時被調(diào)用,onClose在有客戶端斷開連接時被調(diào)用。 這里就可以大概看出如何使用swoole:在onConnect處監(jiān)聽新的連接;在onReceive處接收數(shù)據(jù)并處理,然后可以調(diào)用send函數(shù)將處理結(jié)果發(fā)送出去;在onClose處處理客戶端下線的事件。
下面貼出客戶端的代碼:
<?php
class Client
{
private $client;
public function __construct() {
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect() {
if( !$this->client->connect("127.0.0.1", 9501 , 1) ) {
echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
}
$message = $this->client->recv();
echo "Get Message From Server:{$message}\n";
fwrite(STDOUT, "請輸入消息:");
$msg = trim(fgets(STDIN));
$this->client->send( $msg );
}
}
$client = new Client();
$client->connect();
這里,通過swoole_client創(chuàng)建一個基于TCP的客戶端實例,并調(diào)用connect函數(shù)向指定的IP及端口發(fā)起連接請求。隨后即可通過recv()和send()兩個函數(shù)來接收和發(fā)送請求。需要注意的是,這里我使用了默認的同步阻塞客戶端,因此recv和send操作都會產(chǎn)生網(wǎng)絡(luò)阻塞。
更多建議: