Klienter ansluter till Azure Web PubSub-tjänsten med hjälp av standardprotokollet WebSocket . Du kan använda språk som har WebSocket-klientstöd för att skriva en klient för tjänsten. I den här artikeln visas flera WebSocket-klientexempel på olika språk.
Auktorisering
Web PubSub använder en JSON-webbtoken (JWT) för att verifiera och auktorisera klienter. Klienter kan antingen placera token i access_token frågeparametern eller placera den i Authorization huvudet när de ansluter till tjänsten.
Vanligtvis kommunicerar klienten med sin appserver först för att hämta url:en för tjänsten och token. Sedan öppnar klienten WebSocket-anslutningen till tjänsten med hjälp av den URL och token som den tar emot.
Portalen innehåller också ett verktyg för att generera klient-URL:en med token dynamiskt. Det här verktyget kan vara användbart för att göra ett snabbtest.
Kommentar
Se till att endast inkludera nödvändiga roller när du genererar token.
 
I följande avsnitt, för att förenkla exempelarbetsflödet, använder vi den här tillfälligt genererade URL:en från portalen för att klienten ska kunna ansluta. Vi använder <Client_URL_From_Portal> för att representera värdet. Den token som genereras upphör att gälla om 60 minuter som standard, så glöm inte att återskapa en när token upphör att gälla.
Tjänsten stöder två typer av WebSocket-klienter: den ena är den enkla WebSocket-klienten och den andra är PubSub WebSocket-klienten. Här visar vi hur dessa två typer av klienter ansluter till tjänsten. Mer information om dessa klienter finns i WebSocket-klientprotokoll för Azure Web PubSub.
Dependency
I de flesta moderna webbläsare WebSocket stöds API:et internt.
 
Enkel WebSocket-klient
script Inuti blocket på HTML-sidan:
<script>
    // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
    let ws = new WebSocket("<Client_URL_From_Portal>");
    ws.onopen = () => {
        // Do things when the WebSocket connection is established
    };
    ws.onmessage = event => {
        // Do things when messages are received.
    };
</script>
const WebSocket = require('ws');
// Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
const client = new WebSocket("<Client_URL_From_Portal>");
client.on('open', () => {
     // Do things when the WebSocket connection is established
});
client.on('message', msg => {
     // Do things when messages are received.
});
import asyncio
import websockets
async def hello():
    # Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
    uri = '<Client_URL_From_Portal>'
    async with websockets.connect(uri) as ws:
        while True:
            await ws.send('hello')
            greeting = await ws.recv()
            print(greeting)
asyncio.get_event_loop().run_until_complete(hello())
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Websocket.Client;
namespace subscriber
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
            using (var client = new WebsocketClient(new Uri("<Client_URL_From_Portal>")))
            {
                // Disable the auto disconnect and reconnect because the sample would like the client to stay online even if no data comes in
                client.ReconnectTimeout = null;
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                await client.Start();
                Console.WriteLine("Connected.");
                Console.Read();
            }
        }
    }
}
package client;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
/**
 * A simple WebSocket Client.
 *
 */
public final class SimpleClient {
    private SimpleClient() {
    }
    /**
     * Starts a simple WebSocket connection.
     * @param args The arguments of the program.
     */
    public static void main(String[] args) throws Exception {
        // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
        WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
                .buildAsync(URI.create("<Client_URL_From_Portal>"), new WebSocketClient()).join();
        System.in.read();
    }
    private static final class WebSocketClient implements WebSocket.Listener {
        private WebSocketClient() {
        }
        @Override
        public void onOpen(WebSocket webSocket) {
            System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
            WebSocket.Listener.super.onOpen(webSocket);
        }
        @Override
        public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
            System.out.println("onText received " + data);
            return WebSocket.Listener.super.onText(webSocket, data, last);
        }
        @Override
        public void onError(WebSocket webSocket, Throwable error) {
            System.out.println("Bad day! " + webSocket.toString());
            WebSocket.Listener.super.onError(webSocket, error);
        }
    }
}
 
PubSub WebSocket-klient
script Inuti blocket på HTML-sidan:
<script>
    // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
    let ws = new WebSocket("<Client_URL_From_Portal>", 'json.webpubsub.azure.v1');
    ws.onopen = () => {
        // Do things when the WebSocket connection is established
    };
    ws.onmessage = event => {
        // Do things when messages are received.
    };
</script>
const WebSocket = require('ws');
// Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
const client = new WebSocket("<Client_URL_From_Portal>", "json.webpubsub.azure.v1");
client.on('open', () => {
     // Do things when the WebSocket connection is established
});
client.on('message', msg => {
     // Do things when messages are received.
});
import asyncio
import websockets
async def join_group():
    # Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
    uri = '<Client_URL_From_Portal>'
    async with websockets.connect(uri, subprotocols=['json.webpubsub.azure.v1']) as ws:
        await ws.send('{"type":"joinGroup","ackId":1,"group":"group1"}')
        return await ws.recv()
print(asyncio.get_event_loop().run_until_complete(join_group()))
using System;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
namespace subscriber
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
            using (var client = new WebsocketClient(new Uri("<Client_URL_From_Portal>"), () =>
            {
                var inner = new ClientWebSocket();
                inner.Options.AddSubProtocol("json.webpubsub.azure.v1");
                return inner;
            }))
            {
                // Disable the auto disconnect and reconnect because the sample would like the client to stay online even if no data comes in
                client.ReconnectTimeout = null;
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                await client.Start();
                Console.WriteLine("Connected.");
                Console.Read();
            }
        }
    }
}
package client;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
/**
 * A PubSub WebSocket Client.
 *
 */
public final class SubprotocolClient {
    private SubprotocolClient() {
    }
    /**
     * Starts a PubSub WebSocket connection.
     * @param args The arguments of the program.
     */
    public static void main(String[] args) throws Exception {
        // Don't forget to replace this <Client_URL_From_Portal> with the value fetched from the portal
        WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder().subprotocols("json.webpubsub.azure.v1")
                .buildAsync(URI.create("<Client_URL_From_Portal>"), new WebSocketClient()).join();
        ws.sendText("{\"type\":\"joinGroup\",\"ackId\":1,\"group\":\"group1\"}", true);
        System.in.read();
    }
    private static final class WebSocketClient implements WebSocket.Listener {
        private WebSocketClient() {
        }
        @Override
        public void onOpen(WebSocket webSocket) {
            System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
            WebSocket.Listener.super.onOpen(webSocket);
        }
        @Override
        public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
            System.out.println("onText received " + data);
            return WebSocket.Listener.super.onText(webSocket, data, last);
        }
        @Override
        public void onError(WebSocket webSocket, Throwable error) {
            System.out.println("Bad day! " + webSocket.toString());
            WebSocket.Listener.super.onError(webSocket, error);
        }
    }
}
 
Nästa steg
I den här artikeln har du lärt dig hur du ansluter till tjänsten med hjälp av den URL som genereras från portalen. Om du vill se hur klienterna kommunicerar med appservern för att hämta URL:en i verkliga program läser du de här självstudierna och kollar in exemplen.