Muokkaa

Jaa


Start a WebSocket connection to Azure Web PubSub

Clients connect to the Azure Web PubSub service by using the standard WebSocket protocol. You can use languages that have WebSocket client support to write a client for the service. In this article, you see several WebSocket client samples in different languages.

Authorization

Web PubSub uses a JSON Web Token (JWT) to validate and authorize clients. Clients can either put the token in the access_token query parameter, or put it in the Authorization header when connecting to the service.

Typically, the client communicates with its app server first, to get the URL of the service and the token. Then, the client opens the WebSocket connection to the service by using the URL and token it receives.

The portal also provides a tool to generate the client URL with the token dynamically. This tool can be useful to do a quick test.

Screenshot showing where to find the Client URL Generator.

Note

Make sure to only include necessary roles when you're generating the token.

In the following sections, to simplify the sample workflow, we use this temporarily generated URL from the portal for the client to connect. We use <Client_URL_From_Portal> to represent the value. The token generated expires in 60 minutes by default, so don't forget to regenerate one when the token expires.

The service supports two types of WebSocket clients: one is the simple WebSocket client, and the other is the PubSub WebSocket client. Here we show how these two kinds of clients connect to the service. For more information about these clients, see WebSocket client protocols for Azure Web PubSub.

Dependency

In most modern browsers, WebSocket API is natively supported.

Simple WebSocket client

Inside the script block of the HTML page:

<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>

PubSub WebSocket client

Inside the script block of the HTML page:

<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>

Next steps

In this article, you learned how to connect to the service by using the URL generated from the portal. To see how the clients communicate with the app server to get the URL in real-world applications, read these tutorials and check out the samples.