本篇文章为大家展示了如何在Linux中安装Swoole,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。


下载好放到/usr/local/src下,解压缩:
tar -zxvf swoole-2.2.0.tgz
准备扩展安装编译环境:
phpize

查看php-config位置:
find / -name php-config

配置:(--with-php-config==后面是你自己的php-config位置)
./configure --with-php-config=/www/server/php/72/bin/php-config
编译安装:
make && make install

在php.ini里面加一行 :
extension = swoole.so
使用 php -m 命令查看swoole扩展已经安装成功:

查看phpinfo信息:

(测试前说明:以下使用的端口,要确认服务器放行,宝塔环境还需要添加安全组规则)
【创建TCP服务器】
创建server.php:
on('connect', function ($serv, $fd) {
echo "Client: Connect.\n";
});
//监听数据接收事件
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, "Server: ".$data);
});
//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
//启动服务器
$serv->start();启动TCP服务:
php server.php
查看9501端口已被监听:
netstat -an | grep 9501

使用telnet连接TCP服务,输入hello,服务器返回hello即测试成功:
telnet 127.0.0.1 9501

(如果telnet工具没有安装,执行yum install telnet 、yum install telnet-server)
也可以写一个TCP客户端连接TCP服务器端:
创建tcp_client.php:
connect("127.0.0.1" ,9501)){
echo "连接失败";
exit;
}
//向tcp服务器发送消息
fwrite(STDOUT, "请输入:");
$msg = trim(fgets(STDIN));
$client->send($msg);
//接受tcp服务器消息
$result = $client->recv();
echo $result;启动tcp客户端:
php tcp_client.php
测试结果:

【创建UDP服务器】
创建udp_server.php:
on('Packet', function ($serv, $data, $clientInfo) {
$serv->sendto($clientInfo['address'], $clientInfo['port'], "Server ".$data);
var_dump($clientInfo);
});
//启动服务器
$serv->start();启动UDP服务:
php udp_server.php
查看9502端口已被监听:
netstat -an | grep 9502

使用netcat连接UDP服务,输入hello,服务器返回hello即测试成功(CentOS):
nc -u 127.0.0.1 9502

(如果没有安装netcat监听器,执行yum install -y nc)
【创建Web服务器】
创建http_server.php:
set([
'document_root' => '/www/wwwroot/lwsblog',
'enable_static_handler' => true,
]);
$http->on('request', function ($request, $response) {
var_dump($request->get, $request->post);
//设置header
$response->header("Content-Type", "text/html; charset=utf-8");
//设置cookie
$response->cookie("name", "lws", time()+3600);
//发送Http响应体,并结束请求处理。
$response->end("Hello Swoole. #".rand(1000, 9999)."
");
});
$http->start();启动服务:
php http_server.php
(如果9501端口已经被占用查看进程PID,杀死进程:)

lsof -i:9501

kill 9013
浏览器访问主机地址:端口号,得到程序预期结果即测试成功:

【创建WebSocket服务器】
创建ws_server.php:
set([
'document_root' => '/www/wwwroot/lwsblog',
'enable_static_handler' => true,
]);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();运行程序:(这里还是要确认监听的端口没有被占用,如果被占用查看进程PID,杀死进程)
php ws_server.php
前端页面js监听:(127.0.0.1改成你的主机地址)
WebSocket
使用谷歌浏览器访问前端页面:

服务器端收到请求信息:

上述内容就是如何在Linux中安装Swoole,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。