1、下载 centrifuge.js

2、准备token
centrifugo 的token结构,参见 authentication

sub:用户id
exp:过期时间[可选]
info:附加信息[可选]
b64info:[可选] If you are using binary protobuf protocol you may want info to be custom bytes. Use this field in this case.

这里为了测试方便,我们用一个token.py来实现生成token , secret 是你在centrifugo的config中配置的secret值

import jwt
token = jwt.encode({"sub": "42"}, "secret").decode()
print(token)

执行python token.py得到我们需要的token

>python token.py
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9.cYo84rqiyvYovXGPGxY7a4qWLa5HA857Nb2uMrkVcHs

这里我们用的jwt包是PyJWT ,可以使用pip install PyJWT安装

>pip install PyJWT
Collecting PyJWT
  Downloading https://files.pythonhosted.org/packages/87/8b/6a9f14b5f781697e51259d81657e6048fd31a113229cf346880bb7545565/PyJWT-1.7.1-py2.py3-none-any.whl
Installing collected packages: PyJWT
  The script pyjwt.exe is installed in 'C:UsersNULLAppDataLocalPackagesPythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0LocalCachelocal-packagesPython37Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed PyJWT-1.7.1
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

3、需要的都准备好了,我们写个简单的页面来订阅吧



var centrifuge = new Centrifuge('ws://192.168.56.3:1083/connection/websocket');
centrifuge.setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9.cYo84rqiyvYovXGPGxY7a4qWLa5HA857Nb2uMrkVcHs');



centrifuge.on('connect', function(context) {
    // 现在客户端连接到Centrifugo并获得授权
    console.log('connect');
});

centrifuge.on('disconnect', function(context) {
    // 在与服务器断开连接的情况下,执行任何您需要的操作
    console.log('连接已断开。');
    console.log(context);
});

var callbacks = {
    "publish": function(message) {
        // See below description of message format
        console.log(message);
    },
    "join": function(message) {
        // See below description of join message format
        console.log(message);
    },
    "leave": function(message) {
        // See below description of leave message format
        console.log(message);
    },
    "subscribe": function(context) {
        // See below description of subscribe callback context format
        console.log(context);
    },
    "error": function(errContext) {
        // See below description of subscribe error callback context format
        console.log(err);
    },
    "unsubscribe": function(context) {
        // See below description of unsubscribe event callback context format
        console.log(context);
    }
}

var subscription = centrifuge.subscribe("news", callbacks);

centrifuge.connect();




4、用chrome打开这个页面

TIM截图20190611175816.jpg

看起来已经连上了服务器

5、用服务器推送一条消息试试看效果

TIM截图20190611180005.jpg

6、检查客户端是否接收到消息

TIM截图20190611180101.jpg

文章来源于互联网:GoLang消息推送:在JS中订阅centrifugo的websocket消息服务

发表评论