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
連線到您的 Web PubSub 資源並註冊 ServerMessageReceived 事件的接聽程式
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 服務所需的授權資訊。 連接字串內的存取金鑰類似於您服務的根密碼。
在本快速入門指南中,我們將從 Azure 入口網站取得,如下所示。
執行伺服器程式
在新的命令殼層中,執行下列命令。
# 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 simluates 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)