1. 程式人生 > >swoole 安裝 搭建tcp服務器和websocket

swoole 安裝 搭建tcp服務器和websocket

rms 運行 ins req als request nec 文件 art

1、安裝swoole
wget https://github.com/swoole/swoole-src/archive/v1.9.1-stable.tar.gz
tar zxvf v1.9.1-stable.tar.gz
cd swoole-src-1.9.1-stable
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install
2、配置php支持swoole
vi /usr/local/php/etc/php.ini
添加
extension=swoole.so
3、重啟php-fpm
service php-fpm restart
在phpinfo頁面可以看到關於swoole的選項,說明安裝成功。

4.搭建Echo服務器
服務端 Server
創建一個Server.php文件並輸入如下內容:

// 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,
        ));

        $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";
        $serv->send($fd, $data);
    }

    public function onClose( $serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }
}
// 啟動服務器 Start the server
$server = new Server();

客戶端 Client
創建一個Client.php文件並輸入如下內容:

<?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: {$this->client->errMsg}[{$this->client->errCode}]\n";
        }

        fwrite(STDOUT, "請輸入消息 Please input msg:");  
        $msg = trim(fgets(STDIN));
        $this->client->send( $msg );

        $message = $this->client->recv();
        echo "Get Message From Server:{$message}\n";
    }
}

$client = new Client();
$client->connect();

運行 Run it!
在Terminal下執行命令php Server.php即可啟動服務器,在另一個Terminal下執行php Client.php,輸入要發送的內容,即可發送消息到服務器,並收到來自服務器的消息。

websocket:

$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);

$server->on(‘open‘, function (Swoole\WebSocket\Server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});

$server->on(‘message‘, function (Swoole\WebSocket\Server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "this is server");
});

$server->on(‘close‘, function ($ser, $fd) {
    echo "client {$fd} closed\n";
});

$server->start();

swoole 安裝 搭建tcp服務器和websocket