21
loading...
This website collects cookies to deliver better user experience
WebPubSubEventHandler
and use it as a middleware in the express app.let handler = new WebPubSubEventHandler(hubName, ['*'], {
path: '/eventhandler',
handleConnect: ...
onConnected: ...
onDisconnected: ...
handleUserEvent: ...
});
app.use(handler.getMiddleware());
onConnected
and onDisconnected
, which are similar to open
and close
events in WebSocket, but the key difference here is when using Azure Web PubSub service, the connection is connected to the service, your server just gets a notification when this happens but does not need to manage the lifetime of the connection. This is usually challenging in real scenarios where you need to handle things like connection routing and load balancing. In Azure Web PubSub they're all taken care of by the service.this._webSocket.send(JSON.stringify({
type: 'sendToGroup',
group: group,
dataType: 'json',
data: data
}));
this._webSocket.send(JSON.stringify({
type: 'event',
event: 'message',
dataType: 'json',
data: data
}));
let handler = new WebPubSubEventHandler(hubName, ['*'], {
path: '/eventhandler',
...
handleUserEvent: async (req, res) => {
let message = req.data;
switch (message.name) {
case 'addShape': ...
case 'removeShape': ...
case 'clear': ...
}
res.success();
}
});
diagram
object (for demo purpose, in a real application you should use a persistent storage to store this diagram).You can see there is still data communication between client and server, but comparing to the real-time updates between clients (which happens whenever a user moves their mouse on the screen), this only happens when a user finishes drawing a shape, so the amount of data is much less than the real-time updates.
app.get('/negotiate', async (req, res) => {
let token = await serviceClient.getAuthenticationToken({
roles: ['webpubsub.sendToGroup.draw']
});
res.json({
url: token.url
});
})
let res = await fetch('/negotiate');
let url = res.json().url;
let ws = new WebSocket(url, 'json.webpubsub.azure.v1');
json.webpubsub.azure.v1
subprotocol, you'll be able to join, leave and publish messages from client (more details can be found here).If you don't specify subprotocol you can still connect, but all messages you send will be treated as events and be sent to server.