const { WebPubSubClient } = require("@azure/web-pubsub-client");
// Instantiates the client object
// <client-access-url> is copied from Azure portal mentioned above
const client = new WebPubSubClient("<client-access-url>")
// Registers a handler for the "server-message" event
client.on("server-message", (e) => {
console.log(`Received message ${e.message.data}`)
});
// Before a client can receive a message,
// you must invoke start() on the client object.
client.start();
运行程序
node subscribe.js
现在,此客户端与 Web PubSub 资源建立连接,并准备好接收从应用程序服务器推送的消息。
创建一个名为 subscriber 的项目目录,并安装所需的依赖项
mkdir subscriber
cd subscriber
# Create a .net console app
dotnet new console
# Add the client SDK
dotnet add package Azure.Messaging.WebPubSub.Client --prerelease
using Azure.Messaging.WebPubSub.Clients;
// Instantiates the client object
// <client-access-uri> is copied from Azure portal mentioned above
var client = new WebPubSubClient(new Uri("<client-access-uri>"));
client.ServerMessageReceived += eventArgs =>
{
Console.WriteLine($"Receive message: {eventArgs.Message.Data}");
return Task.CompletedTask;
};
client.Connected += eventArgs =>
{
Console.WriteLine("Connected");
return Task.CompletedTask;
};
await client.StartAsync();
// This keeps the subscriber active until the user closes the stream by pressing Ctrl+C
var streaming = Console.ReadLine();
while (streaming != null)
{
if (!string.IsNullOrEmpty(streaming))
{
await client.SendToGroupAsync("stream", BinaryData.FromString(streaming + Environment.NewLine), WebPubSubDataType.Text);
}
streaming = Console.ReadLine();
}
await client.StopAsync();
mkdir publisher
cd publisher
npm init
# This command installs the server SDK from NPM,
# which is different from the client SDK you used in subscribe.js
npm install --save @azure/web-pubsub
使用以下代码创建 publish.js 文件
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
// This is the hub name we used on Azure portal when generating the Client Access URL.
// It ensures this server can push messages to clients in the hub named "myHub1".
const hub = "myHub1";
let server = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);
// By default, the content type is `application/json`.
// Specify contentType as `text/plain` for this demo.
server.sendToAll(process.argv[2], { contentType: "text/plain" });
server.sendToAll() 调用会将消息发送到中心内所有已连接的客户端。
获取连接字符串
重要
连接字符串包括应用程序访问 Web PubSub 服务所需的授权信息。 连接字符串中的访问密钥类似于服务的根密码。
# Set the environment variable for your connection string.
export WebPubSubConnectionString="<Put your connection string here>"
node publish.js "Hello World"
mkdir publisher
cd publisher
dotnet new console
dotnet add package Azure.Messaging.WebPubSub
将 Program.cs 文件替换为以下代码
using System;
using System.Threading.Tasks;
using Azure.Messaging.WebPubSub;
namespace publisher
{
class Program
{
static async Task Main(string[] args)
{
if (args.Length != 3) {
Console.WriteLine("Usage: publisher <connectionString> <hub> <message>");
return;
}
var connectionString = args[0];
var hub = args[1];
var message = args[2];
// Either generate the token or fetch it from server or fetch a temp one from the portal
var serviceClient = new WebPubSubServiceClient(connectionString, hub);
await serviceClient.SendToAllAsync(message);
}
}
}
SendToAllAsync() 调用会将消息发送到中心内所有已连接的客户端。
运行服务器程序,将消息推送到所有连接的客户端
$connection_string="<connection-string>"
dotnet run $connection_string "myHub1" "Hello World"
观察客户端收到的消息
# On the command shell used for running the "subscribe" program, you should see the received the messaged logged there.
# Try running the same "subscribe" program in multiple command shells, which simulates more than clients.
# Try running the "publish" program several times and you see messages being delivered in real-time to all these clients.
Message received: Hello World
首先,创建一个名为 publisher 的项目目录,并安装所需的依赖项:
mkdir publisher
cd publisher
# Create venv
python -m venv env
# Active venv
source ./env/bin/activate
pip install azure-messaging-webpubsubservice
使用 Azure Web PubSub SDK 将消息发布到服务。 使用以下代码创建一个 publish.py 文件:
import sys
from azure.messaging.webpubsubservice import WebPubSubServiceClient
if __name__ == '__main__':
if len(sys.argv) != 4:
print('Usage: python publish.py <connection-string> <hub-name> <message>')
exit(1)
connection_string = sys.argv[1]
hub_name = sys.argv[2]
message = sys.argv[3]
service = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
res = service.send_to_all(message, content_type='text/plain')
print(res)