使用Websocket+Swoole+CodeIngiter作聊天室

前端H5代碼:php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket = new WebSocket('ws://192.168.122.128:9502');

    // 打開Socket
    socket.onopen = function(event) {
        socket.send('{"user":"<?php echo $user;?>" ,"type":"1"}');
    };
    socket.onmessage=function(event){
     
        var data=eval("("+event.data+")");
        console.log(data);
       document.getElementById('text').value+=data.msg+"\n";
    }
    function sendMessage(touser){
        var msg='{"type":"2","msg":"'+document.getElementById('msgbox').value+'","from_user":"<?php echo $user;?>","touser":"'+touser+'"}';
        socket.send(msg);
    }

</script>
<textarea name="" id="text" cols="30" rows="10"></textarea>
<input type="text" name="msgbox" id="msgbox" />
<button onclick="sendMessage('all');">發送</button>
</body>
</html>

 

後臺CI代碼:html

用戶先登陸,登陸後,進入chat/index頁面前端

include_once('Auth.php');
class Chat extends Auth {
    public function __construct(){
        parent::__construct();
        echo $this->username;
    }

    public function index(){
        $this->load->helper('url');
        $data=array(
            'user'=>$this->username,
        );

        $this->load->view('chat.php',$data);
    }
}

在CLI模式下運行swoole/start 頁面android

cd /mnt/hgfs/wwwroot/chat
php index.php swoole start

 

swoole/start 代碼git

$server = new swoole_websocket_server("0.0.0.0", 9502);

        $server->on('open', function (swoole_websocket_server $server, $request) {
            echo "server: handshake success with fd{$request->fd}\n";
        });

        $server->on('message', function (swoole_websocket_server $server, $frame) {
           // echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";

            $data=(array)json_decode($frame->data,true);
            print_r($data);
            if($data['type']==1){
                echo " {$data['user']} 進入聊天室!\n";
                $this->load->driver('cache');
                $cache=$this->cache->file->get('clients');
                $tmp=array();
                if($cache){
                    $tmp=unserialize($cache);
                    $tmp[$frame->fd]=array(
                        'id'=>$frame->fd,
                        'user'=>$data['user'],
                    );
                    $save=serialize($tmp);
                    $this->cache->file->save('clients',$save,300);
                }else{
                    $tmp[$frame->fd]=array(
                        'id'=>$frame->fd,
                        'user'=>$data['user'],
                    );
                    $this->cache->file->save('clients',serialize($tmp),300);//緩存在線用戶
                }
                foreach($tmp as $v) {
                    $server->push($v['id'], json_encode(array('type' => 1, 'msg' => "歡迎{$data['user']}進入聊天室!")));
                }
            }else if($data['type']==2){
                echo " {$data['from_user']} 對你們說:{$data['msg']} !\n";
                if($data['touser']=='all'){
                    echo '全部用戶';
                    $cache=$this->cache->file->get('clients');
                    $tmp=unserialize($cache);
                    foreach($tmp as $v){
                        $server->push($v['id'],json_encode(array('type'=>2,'msg'=>"用戶{$data['from_user']}對你們說:{$data['msg']} !")));
                    }
                }
            }


        });

        $server->on('close', function (swoole_websocket_server $server, $fd) {
            $cache=$this->cache->file->get('clients');
            $tmp=unserialize($cache);
            unset($tmp[$fd]);
            $this->cache->file->save('clients',serialize($tmp),500);
            echo "client {$fd} closed\n";
            foreach($tmp as $v){
                $server->push($v['id'],json_encode(array('type'=>3,'msg'=>"用戶{$v['user']}離開了聊天室。")));
             }
        });

        $server->start();

 

 

功能比較簡單,結合websocket+CodeIngiter+swoole。web

之後整合到android APP上。json

相關文章
相關標籤/搜索