Skip to main content التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
يتجاوز الأمر المباشر Prompt المخصّص للمراجعة. افحص المصدر قبل تشغيله.
npx skills add https://github.com/BEKO2210/Firstbrain --skill azure-web-pubsub-tsيبقى الأمر في سطر واحد. مرّر أفقيًا لمراجعته كاملًا قبل النسخ.
تفضّل نسخة محلية؟ نزّل الملفات المتاحة حاليًا لدى SkillsMP.
المهن ذات الصلةSOC
استنادا إلى تصنيف SOC المهني
| name | azure-web-pubsub-ts |
| description | Real-time messaging with WebSocket connections and pub/sub patterns. |
| type | skill |
| created | 2026-02-27T00:00:00.000Z |
| domain | cloud-infrastructure |
| category | azure |
| risk | unknown |
| source | community |
| tags | ["skill","cloud-infrastructure","azure","web","pubsub"] |
Azure Web PubSub SDKs for TypeScript
Real-time messaging with WebSocket connections and pub/sub patterns.
Installation
npm install @azure/web-pubsub @azure/identity
npm install @azure/web-pubsub-client
npm install @azure/web-pubsub-express
Environment Variables
WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=<key>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
Server-Side: WebPubSubServiceClient
Authentication
import { WebPubSubServiceClient, AzureKeyCredential } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubServiceClient(
process.env.WEBPUBSUB_CONNECTION_STRING!,
"chat"
);
const client2 = new WebPubSubServiceClient(
process.env.WEBPUBSUB_ENDPOINT!,
new DefaultAzureCredential(),
"chat"
);
const client3 = new WebPubSubServiceClient(
process.env.WEBPUBSUB_ENDPOINT!,
new (),
);
AzureKeyCredential
"<access-key>"
"chat"
Generate Client Access Token
const token = await client.getClientAccessToken();
console.log(token.url);
const userToken = await client.getClientAccessToken({
userId: "user123",
});
const permToken = await client.getClientAccessToken({
userId: "user123",
roles: [
"webpubsub.joinLeaveGroup",
"webpubsub.sendToGroup",
"webpubsub.sendToGroup.chat-room",
],
groups: ["chat-room"],
expirationTimeInMinutes: 60,
});
Send Messages
await client.sendToAll({ message: "Hello everyone!" });
await client.sendToAll("Plain text", { contentType: "text/plain" });
await client.sendToUser("user123", { message: "Hello!" });
await client.sendToConnection("connectionId", { data: "Direct message" });
await client.sendToAll({ message: "Filtered" }, {
filter: "userId ne 'admin'",
});
Group Management
const group = client.group("chat-room");
await group.addUser("user123");
await group.addConnection("connectionId");
await group.removeUser("user123");
await group.sendToAll({ message: "Group message" });
await group.closeAllConnections({ reason: "Maintenance" });
Connection Management
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");
await client.closeConnection("connectionId", { reason: "Kicked" });
await client.closeUserConnections("user123");
await client.closeAllConnections();
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });
Client-Side: WebPubSubClient
Connect
import { WebPubSubClient } from "@azure/web-pubsub-client";
const client = new WebPubSubClient("<client-access-url>");
const client2 = new WebPubSubClient({
getClientAccessUrl: async () => {
const response = await fetch("/negotiate");
const { url } = await response.json();
return url;
},
});
client.on("connected", (e) => {
console.log(`Connected: ${e.connectionId}`);
});
client.on("group-message", (e) => {
console.log(`${e.message.group}: ${e.message.data}`);
});
await client.start();
Send Messages
await client.joinGroup("chat-room");
await client.sendToGroup("chat-room", "Hello!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Hi" }, "json");
await client.sendToGroup("chat-room", "Hello", "text", {
noEcho: true,
fireAndForget: true,
});
await client.sendEvent("userAction", { action: "typing" }, "json");
Event Handlers
client.on("connected", (e) => {
console.log(`Connected: ${e.connectionId}, User: ${e.userId}`);
});
client.on("disconnected", (e) => {
console.log(`Disconnected: ${e.message}`);
});
client.on("stopped", () => {
console.log("Client stopped");
});
client.on("group-message", (e) => {
console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});
client.on("server-message", (e) => {
console.log(`Server: ${e.message.data}`);
});
client.on("rejoin-group-failed", (e) => {
console.log(`Failed to rejoin ${e.group}: ${e.error}`);
});
Express Event Handler
import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
const app = express();
const handler = new WebPubSubEventHandler("chat", {
path: "/api/webpubsub/hubs/chat/",
handleConnect: (req, res) => {
if (!req.claims?.sub) {
res.fail(401, "Authentication required");
return;
}
res.success({
userId: req.claims.sub[0],
groups: ["general"],
roles: ["webpubsub.sendToGroup"],
});
},
handleUserEvent: (req, res) => {
console.log(`Event from ${req.context.userId}:`, req.data);
res.success(`Received: ${req.data}`, "text");
},
onConnected: (req) => {
console.log(`Client connected: ${req.context.connectionId}`);
},
onDisconnected: (req) => {
console.log(`Client disconnected: ${req.context.connectionId}`);
},
});
app.use(handler.getMiddleware());
app.get("/negotiate", async (req, res) => {
const token = await serviceClient.getClientAccessToken({
userId: req.user?.id,
});
res.json({ url: token.url });
});
app.listen(8080);
Key Types
import {
WebPubSubServiceClient,
WebPubSubGroup,
GenerateClientTokenOptions,
HubSendToAllOptions,
} from "@azure/web-pubsub";
import {
WebPubSubClient,
WebPubSubClientOptions,
OnConnectedArgs,
OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";
import {
WebPubSubEventHandler,
ConnectRequest,
UserEventRequest,
ConnectResponseHandler,
} from "@azure/web-pubsub-express";
Best Practices
- Use Entra ID auth -
DefaultAzureCredential for production
- Register handlers before start - Don't miss initial events
- Use groups for channels - Organize messages by topic/room
- Handle reconnection - Client auto-reconnects by default
- Validate in handleConnect - Reject unauthorized connections early
- Use noEcho - Prevent message echo back to sender when needed
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
Connections
- Domain: [[Cloud & Infrastruktur]]
- Kategorie: [[Microsoft Azure]]
- Navigation: [[Skills Uebersicht]], [[Home]]