1.安裝準備php
php-5.3.10 // 或更高版本 gcc-4.4 //或更高版本 make autoconf
2.安裝swoole擴展git
wget https://github.com/swoole/swoole-src/archive/swoole-1.8.2-stable.tar.gz tar -zxvf swoole-1.8.2-stable cd swoole-src-swoole-1.8.2-stable/ /usr/local/php/bin/phpize ./configure make && make install
3.配置php支持swoolegithub
編輯php.ini 在其中加入擴展支持 extension=swoole.so
4.swoole 服務端代碼 server.phpswoole
<?php /** * 服務端 */ $serv = new swoole_server("0.0.0.0", 9501); $serv->on('connect', function ($serv, $fd){ echo "Client:Connect.\n"; }); $serv->on('receive', function ($serv, $fd, $from_id, $data) { $serv->send($fd, 'Swoole: '.$data); }); $serv->on('close', function ($serv, $fd) { echo "Client: Close.\n"; }); $serv->start();
5.swoole 客戶端代碼 client.phpsocket
<?php $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $client->on("connect", function($cli) { $cli->send("hello world\n"); }); $client->on("receive", function($cli, $data){ echo "Receive: $data\n"; }); $client->on("error", function($cli){ echo "connect fail\n"; }); $client->on("close", function($cli){ echo "close\n"; }); $client->connect('127.0.0.1', 9501, 0.5);
6.測試代碼測試
在cli命令模式下輸入 php ./server.php 從新再開一個窗口 php ./client.php
能夠用 telnet檢測
如:telnet 127.0.0.1 8088spa
服務端:code
客戶端:server
如上,表示服務端啓動,客戶端鏈接服務端返回消息,一個socket閉環造成
swoole 開發者頭條blog