swoole结合jwt实现websocket登录认证群聊天功能

<a href='/tag/swoole.html'>swoole</a>结合jwt实现websocket登录认证群聊天功能

今天我们用swoole作为websocket服务器,结合jwt来实现在php中登录进行websocket群聊效果。

1、首先使用swoole实现一个websocket服务。

<?php
require "Jwt.php";
$_uselist = [];
$server = new swoole_websocket_server("0.0.0.0", 9502);

$server->on('open', function ($server, $request) {
    $key = 'swoole';
    $token = $request->get['token'] ?? '';

    $decode = Jwt::verifyToken($token);

    if (!$decode) {

        $server->close($request->fd);
        return false;
    }

    $decodeArray = (array)$decode;
    $server->push($request->fd, "hello;" . $decodeArray['name'] . "\n");

    global  $_uselist;
    $_uselist[$request->fd] = $decodeArray['name'];
});

$server->on('message', function (swoole_websocket_server $server, $request) {
    global  $_uselist;
    foreach ($_uselist as $key=>$val) {
        $server->push($key, $_uselist[$request->fd]."说:".$request->data);
    }
   
});

$server->on('close', function ($server, $fd) {
    global  $_uselist;
    unset($_uselist[$fd]);
    var_dump($_uselist);
    echo "client-{$fd} is closed\n";
    $server->close($fd);
});

$server->start();


2、新建login.php用户账号密码认证,代码如下:

<?php
require "Jwt.php";
if (isset($_POST['username'])&&isset($_POST['passwd'])) {
   //此处进行账号密码验证通过后将token写入jwt传给前端
    $key = "swoole";
    $token = array(
        "iss" => "localhost",
        "aud" => "localhost",
        "iat" => time(),
        "nbf" => time()  + 3600,
        "name" => $_POST['name']
    );
    $token = array('iss' => 'admin','name'=>$_POST['username'], 'iat' => time(), 'exp' => time()+7200, 'nbf' => time(), 'sub' => 'www.bfw.wiki', 'jti' => md5(uniqid('JWT').time()));;

    $jwt = Jwt::getToken($token);
    echo $jwt;
    die();
}

?>

3、使用html结合js的websocket实现登录前端和群聊,代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>swoole chat room</title>
    <meta charset="UTF-8">
    <script type="text/javascript">
        if (window.WebSocket) {
            // 端口和ip地址对应不要写错

            var login = function () {
                var name = document.getElementById('name').value;
                var data = new FormData();
                data.append('username', name);
                data.append('passwd', "123456");
                var request = new XMLHttpRequest();
                request.open("post", 'login.php');
                request.send(data);
                request.onload = function() {
                    if (request.readyState === 4 && request.status == 200) {
                        var webSocket = new WebSocket("ws://web.debug.only.bfw.wiki:9502?token=" + request.responseText);
                        webSocket.onopen = function (event) {
                            //webSocket.send("Hello,WebSocket!");
                        };
                        webSocket.onmessage = function (event) {
                            var content = document.getElementById('content');
                            content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">'+event.data+'</p>');
                        };

                        // 处理发送事件

                        var sendButton = document.getElementById('send');
                        sendButton.disabled = false;
                        sendButton.innerHTML = '发送';
                        sendButton.onclick = function() {
                            var data = document.getElementById('message').value;
                            webSocket.send(data);
                        };
                    } else {
                        alert('error');
                    }
                };

            }
        } else {
            console.log("您的浏览器不支持WebSocket");
        }
    </script>
</head>
<body>
    <div style="width:600px;margin:0 auto;border:1px solid #ccc;">
        <div style="height:40px">
            <input type="text" id="name" style="margin-left:10px;height:25px;width:450px;">
            <buttonBfwOnclick="login()" style="height:28px;width:75px;">登录</button>
        </div>
        <hr />
        <div id="content" style="overflow-y:auto;height:300px;"></div>
        <hr />
        <div style="height:40px">
            <input type="text" id="message" style="margin-left:10px;height:25px;width:450px;">
            <button id="send" style="height:28px;width:75px;" disabled="disabled">登录后可以发送</button>
        </div>
    </div>
</body>
</html>


Jwt.php代码如下:

赠送一块钱辛苦费才能看到下面的内容

{{collectdata}}

网友评论0