swoole实战案例解析,即时沟通技术~

客户的即时沟通系统上线,是一个心理咨询平台,心理咨询师和咨询者一对一即时沟通~

 

1.需要linux服务器安装swoole

pecl install swoole

2.关闭防火墙或者添加端口9508

service iptables stop

3.如果用户是阿里云的服务器,注意一定要在安全组中添加9508端口(MDZZ这个弄了半天,一直以为是服务器安装swoole的问题)

4.PHP抒写后端代码(我们项目使用的TP3.2框架)

 

<?php
// +----------------------------------------------------------------------+
// | PHP version 5.5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2013-2015                                  |
// +----------------------------------------------------------------------+
// | Authors: Original Author                      |
// | 微信基本接口模块 继承 Base 控制器                              |
// +----------------------------------------------------------------------+
//
namespace System\Controller;
use Think\Controller;
use Wechat\Serve\Http;
use Wechat\Serve\Token;
class SwooleController extends Controller {

    
    
    
    //初始化程序
    public function index(){
        
        
        echo '正在启动程序' . PHP_EOL;
        
        $this->server = new \swoole_websocket_server("0.0.0.0", 9501);
        
        //第一次连接的时候
        $this->server->on('open', function (\swoole_websocket_server $server, $request) {
            
            echo "新用户连接 fd是 {$request->fd}".PHP_EOL;
        });

        
        
        $this->server->on('message', function (\swoole_websocket_server $server, $frame) {
            
            //收到用户信息
            
            //解析用户数据信息
            $data = json_decode($frame->data,true);
            
            
            //是否为第一次连接
            if($data['type']=='init'){
                
                //缓存用户信息
                S(md5($data['uid']),$frame->fd);
                S($frame->fd,md5($data['uid']));
                
                echo '用户'.$data['uid'].'注册成功'.PHP_EOL;
                
            }else{
                if( !S(md5($data['tid']))  ){
                    $server->push($frame->fd, '{"type":"notice","message":"用户不在线"}');
                    
                }else{
                    //否则推送消息给其他用户
                    $this->server->push(S(md5($data['tid'])), $frame->data);    
                    
                    echo '发送给消息人'.$data['tid'].'的消息已经发送成功'.PHP_EOL;
                    echo '他的FD为'.S(md5($data['tid'])).PHP_EOL;
                }
            }
            
            
            echo "接受到信息来自 {$frame->fd} ".PHP_EOL;
            echo " 内容 {$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}".PHP_EOL;
        });
        
        
        
        //退出事件监控
        $this->server->on('close', function ($ser, $fd) {
            echo "用户 {$fd} 退出聊天系统" . PHP_EOL;
            S(md5(S($frame->fd)),null);
            S($frame->fd,null);
        });
        
        echo '程序启动完毕 启动时间:' . date('Y-m-d H:i:s') . PHP_EOL;
        //启动程序
        $this->server->start();    
        
        
        
    }

    
    
    

    
}

 

5.添加页面前端代码

<script>
//websocket长连接方式,swoole方式
    var wsServer = 'ws://IP地址:9501';
    ws = new WebSocket(wsServer);
    var uid = {$uid};
    var callid = {$callid};
    ws.onopen = function(){
    console.log("socket连接已打开");
    data = {
      uid:uid,
      type:'init',
    };
    ws.send(JSON.stringify(data));
    };
    
    ws.onmessage = function(e){
    console.log("message:" + e.data);
        if(e.data)
        {
            info = $.parseJSON(e.data);
            type = info.type;
            msgid = info.msgid;
            
            // 推送消息到对方客户端
            $.post('/wechat/chat/success',{msgid:msgid},function(data){
              if(data.error==200)
              {
                for_bottom();
                $('.speak_box').append(data.data);

              }
            });


            
        }

    };
    ws.onclose = function(){
    console.log("socket连接已断开");
    };
    ws.onerror = function(e){
    console.log("ERROR:" + e.data);
    };
    //离开页面时关闭连接
    $(window).bind('beforeunload',function(){
    ws.close();
    }
    );
</script>

6.linux服务器运行你的后端代码

php  index.php system/swoole  &  (加入和号是运行后台运行)

7.前台刷新页面,看console 提示socket打开成功就可以了。进行及时沟通了~

 

特步短袖t恤男纯棉2019夏季新款

posted @ 2017-11-24 17:21  feimengv  阅读(3496)  评论(0编辑  收藏  举报