swoole学习笔记
一、linux安装swoole环境
1、安装php扩展
1
| yum install php php-pear php-devel httpd gcc
|
2、安装swoole
3、修改php.ini
4、说明
如果安装了宝塔面板,可以在php版本扩展中找到swoole的扩展,一键安装
二、swoole服务搭建
1、TCP连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <?php
$host = '0.0.0.0'; $port = 9501;
$serv = new swoole_server($host,$port);
$serv->on('connect',function ($serv,$fd){
echo '建立连接成功'; }); $serv->on('receive',function ($serv,$fd,$from_id,$data){ echo '接收到数据'; var_dump($data); }); $serv->on('close',function (){ echo '连接关闭'; }); $serv->start();
|
2、UDP连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php
$host = '0.0.0.0'; $port = 9502; $serv = new swoole_server($host,$port,SWOOLE_PROCESS,SWOOLE_SOCK_UDP);
$serv->on('packet',function ($serv,$data,$fd){ $serv->sendto($fd['address'],$fd['port'],"server: $data"); var_dump($fd); }); $serv->start();
|
3、http
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php //HTTP $host = '0.0.0.0'; $port = 9501; $serv = new swoole_http_server($host, $port); /* * $request:请求信息,get post * $response:返回信息 */ $serv->on('request', function ($request, $response) { //发送数据到相应的客户端,反馈信息 var_dump($request); $response->header("Content-type", "text/html;charset=utf-8");//设置返回头信息 $response->end("hello world" . rand(100, 999)); }); $serv->start();//启动服务
|
4、websocket
- new swoole_websocket_server() //实例化websocket
- swoole_websocket_server //继承自swoole_http_server
- on/start函数
- open/message/close 建立连接/获取信息/关掉链接
- push()发送数据//发送信息给客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?php
$ws = new swoole_websocket_server("0.0.0.0",9501);
$ws->on('open',function ($ws,$request){ var_dump($request); $ws->push($request->fd,"welcome \n"); });
$ws->on('message',function ($ws,$request){ echo 'message: '.$request->data; $ws->push($request->fd,"get it message"); });
$ws->on('close',function ($ws,$request){ echo 'close \n'; }); $ws->start();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket</title> </head> <body> <script> // webSocket用户端 var wsServer = "ws://192.168.72.2:9501"; var webSocket = new WebSocket(wsServer); webSocket.onopen = function (evt) { console.log('链接成功'); } webSocket.onclose = function (evt) { console.log('关闭'); } webSocket.onmessage = function (evt) { console.log(evt.data); } webSocket.onerror = function (evt,e) { console.log('error'); } </script> </body> </html>
|
5、测试工具
NetAssist
三、