0

我正在寻求在 Azure PubSub 中使用组,但似乎我的发布者和订阅者没有以某种方式加入同一个组,或者我的无服务器函数在消息发布后没有处理广播。如果我在未实施组的情况下发布该服务,但一旦我尝试添加组,我可以看到消息在 azure 上命中实时跟踪工具,但之后没有消息发送,所以我怀疑我的 azure 函数中可能遗漏了一些东西,但我不确定那会是什么。

发布者代码:

const hub = "simplechat";
let service = new WebPubSubServiceClient("Endpoint=endpointURL", hub);

// by default it uses `application/json`, specify contentType as `text/plain` if you want plain-text
const group = service.group("myGroup");
group.sendToAll('Hello World', { contentType: "text/plain" }); 

订阅者代码:

const WebSocket = require('ws');
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
var printer = require("printer/lib");
var util = require('util');

async function main() {
  const hub = "simplechat";
  let service = new WebPubSubServiceClient("EndpointEndpointURL", hub);
  const group = service.group("myGroup");
  let token = await service.getClientAccessToken();
  let ws = new WebSocket(token.url, 'json.webpubsub.azure.v1');
  ws.on('open', () => console.log('connected'));
  ws.on('message', data => {
    console.log('Message received: %s', data);
  });
}

main();
4

1 回答 1

0

我认为您错过了将订阅者加入群组的部分。

最简单的方法是给连接一个用户名,并addUser在连接连接时调用将连接添加到组中:

async function main() {
  const hub = "simplechat";
  let service = new WebPubSubServiceClient("EndpointEndpointURL", hub);
  const group = service.group("myGroup");
  let token = await service.getClientAccessToken({ userId: "user1"});
  // with this approach, the WebSocket actually does not need to be 'json.webpubsub.azure.v1' subprotocol, a simple WebSocket connection also works
  let ws = new WebSocket(token.url, 'json.webpubsub.azure.v1');
  ws.on('open', () => {
    console.log('connected');
    group.addUser("user1");
    }
  );
  ws.on('message', data => {
    console.log('Message received: %s', data);
  });
}

或者您可以等到收到已连接响应以获取connectionId连接并调用addConnection以将订阅者添加到组中。

另一种方式,因为您已经在使用json.webpubsub.azure.v1协议,所以您的订阅者发送joinGroup请求:

async function main() {
  const hub = "simplechat";
  let service = new WebPubSubServiceClient("EndpointEndpointURL", hub);
  // make sure you set the joinLeaveGroup role for the group
  let token = await service.getClientAccessToken({
    roles: ['webpubsub.joinLeaveGroup.myGroup']
  });
  let ws = new WebSocket(token.url, 'json.webpubsub.azure.v1');
  let ackId = 0;
  ws.on('open', () => { 
        console.log('connected');
        ws.send(JSON.stringify({
          type: 'joinGroup',
          group: 'myGroup',
          ackId: ++ackId,
        }));
     });
  ws.on('message', data => {
    console.log('Message received: %s', data);
  });
}

当您的订阅者收到此操作的AckMessagejoinGroup时,您的订阅者成功加入该组。

于 2022-02-25T07:54:51.443 回答