欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swoole+Redis+webSocket实现点对点即时聊天

程序员文章站 2022-05-21 14:19:06
...

Swoole+Redis+webSocket实现点对点即时聊天,以下是代码+效果截图:

Server.php:

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

$server->on('open', function($server, $req) {
    echo "connection open: {$req->fd}\n";
});

$server->on('message', function($server, $frame) {
    echo "received message: {$frame->data}\n";
    $receive_data=json_decode($frame->data);
    $redis=new Redis();
    $redis->connect('127.0.0.1', 6379);
    if($receive_data->type=='bind'){
        //关系绑定
        $redis->set('fd_'.$receive_data->name,$frame->fd);
        $redis->set('name_'.$frame->fd,$receive_data->name);
    }else{
        //消息发送
        $data['fd']=$frame->fd;
        $data['name']=$receive_data->name;
        $data['data']=$receive_data->msg;
        $server->push($redis->get('fd_'.$receive_data->touser), json_encode($data));
        $server->push($frame->fd, json_encode($data));
    }
});

$server->on('close', function($server, $fd) {
    echo "connection close: {$fd}\n";
    //取消关系绑定
    $redis=new Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->del('fd_'.$redis->get('name_'.$fd));
    $redis->del('name_'.$fd);
});

$server->on('Shutdown', function($server) {
    //kill -15 PID 才会触发
    echo "Shutdown。。。\n";
    $redis=new Redis();
    $redis->connect('127.0.0.1', 6379);
    //取消所有关系绑定
    foreach($server->connections as $fd)
    {
        $redis->del('fd_'.$redis->get('name_'.$fd));
        $redis->del('name_'.$fd);
    }
});

$server->start();

 

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<style>
    ul,li{list-style: none;padding: 0;margin: 0;}
    body{width: 50%;float: left;margin: 5px 25%;}
    .msg_box{width: 100%;border:1px solid #ddd;height: 500px; float: left;overflow: scroll;}
    .msg_box li{padding: 10px;border-bottom:1px solid #ddd;}
    .op_box{width: 100%;float: left;}
    .op_box textarea{width: 96%;float: left;padding: 2%;border:1px solid #ddd;height: 50px;resize: none;}
    .op_box a{width: 200px;display: block;float: right;height: 30px;line-height: 30px;background: #ddd;color: black;text-align: center;text-underline-style: none;margin-top: 5px;}

</style>
<body>
<ul class="msg_box"></ul>
<div class="op_box">
    <textarea name="msg" placeholder="请输入消息"></textarea>
    <a href="javascript:;" class="send_btn">发送</a>
</div>
</body>
<script>
    var data='';
    var name = window.prompt('请输入昵称', 'jungshen');
    var touser=window.prompt('请输入好友昵称', 'mirror');
    $('title').html('您是:'+name+'正在与'+touser+'聊天_'+$('title').html());
    if(name){
        var ws = new WebSocket("ws://192.168.91.136:9502");

        ws.onopen = function(evt) {
            console.log("Connection open ...");
            //ws.send("Hello WebSockets!");
            data={'name':name,'type':'bind'}
            ws.send(JSON.stringify( data ));
        };

        ws.onmessage = function(evt) {
            console.log( "Received Message: " + evt.data);
            dataObj=eval('('+evt.data+')');
            $('.msg_box').append('<li>'+dataObj.name+':'+dataObj.data+'</li>')
            //ws.close();
        };
        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
        ws.onerror = function(evt) {
            console.log('error');
        };
    }


    $('.send_btn').click(function(){
        var msg=$('textarea').val();
        if(msg){
            data={'name':name,'msg':msg,'type':'msg','touser':touser}
            ws.send(JSON.stringify( data ));
            $('textarea').val('');
        }
    });
    document.onkeydown=function(event){
        if(event.keyCode==13)
        {
            $('.send_btn').click();
            return false;
        }
    }

</script>
</html>

 

效果图:

Swoole+Redis+webSocket实现点对点即时聊天

Swoole+Redis+webSocket实现点对点即时聊天

Swoole+Redis+webSocket实现点对点即时聊天