Swoole 安装 使用

来源:互联网 发布:有了源码怎么做软件 编辑:程序博客网 时间:2024/06/07 06:12

安装一、编译

安装准备

安装swoole前必须保证系统已经安装了下列软件

php-5.3.10 或更高版本gcc-4.4 或更高版本makeautoconf

下载地址

  • https://github.com/swoole/swoole-src/releases
  • http://pecl.php.net/package/swoole
  • http://git.oschina.net/swoole/swoole

下载源代码包后,在终端进入源码目录,执行下面的命令进行编译和安装

cd swoolephpize./configuremake sudo make install

安装二、PECL

swoole项目已收录到PHP官方扩展库,除了手工下载编译外,还可以通过PHP官方提供的pecl命令,一键下载安装swoole

pecl install swoole



配置php.ini

编译安装成功后,修改php.ini加入

extension=swoole.so

通过php -mphpinfo()来查看是否成功加载了swoole,

如果没有可能是php.ini的路径不对,可以使用php -i |grep php.ini来定位到php.ini的绝对路径。






做一个聊天室

服务器端:socket.php

//创建websocket服务器对象,监听0.0.0.0:9502端口$ws = new swoole_websocket_server("0.0.0.0", 9502);//监听WebSocket连接打开事件$ws->on('open', function ($ws, $request) {    $fd[] = $request->fd;    $GLOBALS['fd'][] = $fd;    //$ws->push($request->fd, "hello, welcome\n");});//监听WebSocket消息事件$ws->on('message', function ($ws, $frame) {    $msg =  'from'.$frame->fd.":{$frame->data}\n";//var_dump($GLOBALS['fd']);//exit;    foreach($GLOBALS['fd'] as $aa){        foreach($aa as $i){            $ws->push($i,$msg);        }    }   // $ws->push($frame->fd, "server: {$frame->data}");    // $ws->push($frame->fd, "server: {$frame->data}");});//监听WebSocket连接关闭事件$ws->on('close', function ($ws, $fd) {    echo "client-{$fd} is closed\n";});$ws->start();



客户端:Socket.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div id="msg"></div><input type="text" id="text"><input type="submit" value="发送数据" onclick="song()"></body><script>    var msg = document.getElementById("msg");    var wsServer = 'ws://192.168.1.253:9502';    //调用websocket对象建立连接:    //参数:ws/wss(加密)://ip:port (字符串)    var websocket = new WebSocket(wsServer);    //onopen监听连接打开    websocket.onopen = function (evt) {        //websocket.readyState 属性:        /*        CONNECTING    0    The connection is not yet open.        OPEN    1    The connection is open and ready to communicate.        CLOSING    2    The connection is in the process of closing.        CLOSED    3    The connection is closed or couldn't be opened.        */        msg.innerHTML = websocket.readyState;    };    function song(){        var text = document.getElementById('text').value;        document.getElementById('text').value = '';        //向服务器发送数据        websocket.send(text);    }      //监听连接关闭//    websocket.onclose = function (evt) {//        console.log("Disconnected");//    };    //onmessage 监听服务器数据推送    websocket.onmessage = function (evt) {        msg.innerHTML += evt.data +'<br>';//        console.log('Retrieved data from server: ' + evt.data);    };//监听连接错误信息//    websocket.onerror = function (evt, e) {//        console.log('Error occured: ' + evt.data);//    };</script></html>





安装来源:https://wiki.swoole.com/wiki/page/6.html

使用来源:http://www.jianshu.com/p/fedbb9d2d999

0 0
原创粉丝点击