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

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

场景

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

webSocket服务端代码

我们需要通过Laravel Command来实现,因为Swoole只能运行在PHP CLI模式下。

1.生成Command类

php artisan make:command SwooleServer

2.编写webSocket Server逻辑

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class SwooleServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:server';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole websocket';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $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);
            $redis->auth('123456');

            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->auth('123456');
            
            $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);
            $redis->auth('123456');

            //取消所有关系绑定
            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://172.20.31.192: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>

预览

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知其黑、受其白

喝个咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值