关于在linux中,如何搭建环境然后加载swoole扩展,本文不论述。
1.创建Server.php和Client
在htdocs文件夹下创建Server.php(当然如果你自定义了路径,就另当别论了)
cd /usr/lcoal/httpd/htdocs
vi Server.php
这里使用easyswoole文档中的范例程序
https://linkeddestiny.gitbooks.io/easy-swoole/content/book/chapter01/echo_server.html
// 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同理
<?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();
2.使用Server.php
php /usr/local/httpd/htdocs/Server.php
如果出现错误,说明你已经开启了端口,查看端口关闭,在执行就行了
[2019-04-23 14:55:24 @10601.0] WARNING swSocket_bind(:428): bind(0.0.0.0:9501) failed, Error: Address already in use[98]
PHP Fatal error: Uncaught Swoole\Exception: failed to listen server port[0.0.0.0:9501], Error: Address already in use[98] in /usr/local/httpd/htdocs/Server.php:8
Stack trace:
#0 /usr/local/httpd/htdocs/Server.php(8): Swoole\Server->__construct('0.0.0.0', 9501)
#1 /usr/local/httpd/htdocs/Server.php(40): Server->__construct()
#2 {main}
thrown in /usr/local/httpd/htdocs/Server.php on line 8Fatal error: Uncaught Swoole\Exception: failed to listen server port[0.0.0.0:9501], Error: Address already in use[98] in /usr/local/httpd/htdocs/Server.php:8
Stack trace:
#0 /usr/local/httpd/htdocs/Server.php(8): Swoole\Server->__construct('0.0.0.0', 9501)
#1 /usr/local/httpd/htdocs/Server.php(40): Server->__construct()
#2 {main}
thrown in /usr/local/httpd/htdocs/Server.php on line 8
netstat -anp|grep 9501
kill -9 +上一步获取的端口 如:kill -9 9719
3.开启客户端Client.php
开启一个客户端,输入
php /usr/local/httpd/htdocs/Client.php
4.测试
在客户端输入内容
服务端显示如下:
Get Message From Client 1:156165
[2019-04-23 14:34:58 *10389.7] NOTICE swFactoryProcess_finish (ERRNO 1004): send 6 byte failed, because connection[fd=1] is closed
Client 1 close connection
echo server快速搭建成功。