NodeJS Azure Web PubSub浏览器客户端未接收消息

jk9hmnmh  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(151)

我正在尝试使用Azure Web PubSub从运行在服务器上的Node应用程序向浏览器发送消息。我通过Node应用程序向一个组发送消息,在Azure Cloud Shell中,我可以看到消息可以由Azure CLI接收。但是浏览器客户端不接收任何消息。
我是否可以检查其他内容,以了解为什么Cloud Shell中的Azure CLI正在接收消息,而我的浏览器客户端却没有?

节点服务器应用代码片段(在我的开发机器上本地运行)

const hub = 'myHub';
const key = new AzureKeyCredential('<valid Azure Web PubSub key>');
const service = new WebPubSubServiceClient('https://mydomain.webpubsub.azure.com', key, hub);
const groupClient = service.group('pubsubGroup');

// ..

let msg = 'some text';
groupClient.sendToAll({ messsage: msg }).then(() => {
   console.log(msg);
});

浏览器客户端代码(本地运行的网页中,http://localhost:5000)

<html>
    <head>
        <script>
            (async function () {
                // get token from local node web backend
                let res = await fetch('http://localhost:8000/getPubSubUrl');
                let data = await res.json();
                let ws = new WebSocket(data.url, 'json.webpubsub.azure.v1');
                ws.onopen = () => {
                    // this code is always reached
                    console.log('connected');
                };

                ws.onclose = () => {
                    // this code is never reached, no premature socket closures
                    console.log('socket closed');
                }

                let output = document.querySelector('#container');

                ws.onmessage = event => {
                    // this code is only called once with a system message when the socket connects, never after
                    let d = document.createElement('p');
                    d.innerText = event.data;
                    output.appendChild(d);
                };
            })();            
        </script>
    </head>
    <body>
        <div id="container">

        </div>
    </body>
</html>

Node Express Web后端提供PubSub令牌URL

let cnxn = '<valid connection string from Azure Portal>';
let service = new WebPubSubServiceClient(cnxn, 'myHub');

App.get('/getPubSubUrl', async (req, res) => {
    let token = await service.getClientAccessToken({
        roles: ['webpubsub.sendToGroup.pubsubGroup', 'webpubsub.joinLeaveGroup.pubsubGroup']
    });
    res.send({
        url: token.url
    });
});

Azure Cloud Shell命令和输出

myuser@Azure:~$ az webpubsub client start --name "<valid pubsub resource>" --resource-group "<valid resource group>" --hub-name "myHub"
joingroup pubsubGroup
{"type":"message","from":"group","fromUserId":null,"group":"pubsubGroup","dataType":"json","data":{"messsage":"valid message from my node server app!"}}
1tu0hz3e

1tu0hz3e1#

我错过了一个步骤,它在其他地方有文档记录,但在任何标准示例中都不存在(据我所知)。仅仅从绑定到组的角色生成URI是不够的,您必须向URI发送一个Web Socket字符串消息,要求显式加入组:
在网页脚本中:

ws.onopen = () => {
    console.log('connected');

    // need to explicitly join the group!
    let ackId = 0;
    ws.send(JSON.stringify({
        type: 'joinGroup',
        group: 'pubsubGroup',
        ackId: ++ackId
    }));
};

相关问题