Skip to content

Commit 3e87b4b

Browse files
committed
Update
1 parent 8a9c683 commit 3e87b4b

File tree

1 file changed

+47
-30
lines changed

1 file changed

+47
-30
lines changed

articles/azure-web-pubsub/tutorial-build-chat.md

Lines changed: 47 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
424424
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
425425
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
426426
import com.google.gson.Gson;
427+
import com.google.gson.JsonElement;
427428
import com.google.gson.JsonObject;
428429
import io.javalin.Javalin;
429430
@@ -696,7 +697,12 @@ For now, you need to implement the event handler by your own in Java. The steps
696697
} else if ("azure.webpubsub.user.message".equals(event)) {
697698
String id = ctx.header("ce-userId");
698699
String message = ctx.body();
699-
service.sendToAll(String.format("{\"from\":\"%s\",\"message\":\"%s\"}", id, message), WebPubSubContentType.APPLICATION_JSON);
700+
Gson gson = new Gson();
701+
JsonObject jsonObject = new JsonObject();
702+
jsonObject.addProperty("from", id);
703+
jsonObject.addProperty("message", message);
704+
String messageToSend = gson.toJson(jsonObject);
705+
service.sendToAll(messageToSend, WebPubSubContentType.APPLICATION_JSON);
700706
}
701707
ctx.status(200);
702708
});
@@ -896,9 +902,9 @@ Open `http://localhost:8080/index.html`. You can input your user name and start
896902
897903
## Lazy Auth with `connect` event handler
898904
899-
In previous sections, we demonstrate how to use [negotiate](#add-negotiate-endpoint) endpoint to return the Web PubSub service URL and the JWT access token for the clients to connect to Web PubSub service. In some cases, for example, edge devices that have limited resources, clients might prefer direct connect to Web PubSub resources. In such cases, you can configure `connect` event handler to lazy auth the clients, assign user ID to the clients, specify the groups the clients join once they connect, configure the permissions the clients have and WebSocket subprotocol as the WebSocket response to the client, etc. Details please refer to [connect event handler spec](./reference-client-events.md#connect).
905+
In previous sections, we demonstrate how to use [negotiate](#add-negotiate-endpoint) endpoint to return the Web PubSub service URL and the JWT access token for the clients to connect to Web PubSub service. In some cases, for example, edge devices that have limited resources, clients might prefer direct connect to Web PubSub resources. In such cases, you can configure `connect` event handler to lazy auth the clients, assign user ID to the clients, specify the groups the clients join once they connect, configure the permissions the clients have and WebSocket subprotocol as the WebSocket response to the client, etc. Details please refer to [connect event handler spec](./reference-cloud-events.md#connect).
900906
901-
Now let's use `connect` event handler to acheive the similar as what the [negotiate](#negotiate) section does.
907+
Now let's use `connect` event handler to acheive the similar as what the [negotiate](#add-negotiate-endpoint) section does.
902908
903909
### Update hub settings
904910
@@ -1007,10 +1013,8 @@ app.listen(8080, () => console.log("server started"));
10071013
10081014
# [Java](#tab/java)
10091015
Now let's add the logic to handle the connect event `azure.webpubsub.sys.connect`:
1016+
10101017
```java
1011-
import com.google.gson.Gson;
1012-
import com.google.gson.JsonElement;
1013-
import com.google.gson.JsonObject;
10141018
10151019
// validation: https://learn.microsoft.com/azure/azure-web-pubsub/reference-cloud-events#protection
10161020
app.options("/eventhandler", ctx -> {
@@ -1021,22 +1025,30 @@ app.options("/eventhandler", ctx -> {
10211025
app.post("/eventhandler", ctx -> {
10221026
String event = ctx.header("ce-type");
10231027
if ("azure.webpubsub.sys.connect".equals(event)) {
1024-
System.out.println("Connecting.");
1028+
String body = ctx.body();
1029+
System.out.println("Reading from request body...");
10251030
Gson gson = new Gson();
1026-
JsonObject requestBody = gson.fromJson(ctx.body(), JsonObject.class); // Parse JSON request body
1027-
if (requestBody.has("query")) {
1028-
JsonElement queryElement = requestBody.get("query");
1029-
if (queryObject.has("id")) {
1030-
ctx.status(200);
1031-
String id = queryObject.get("id").getAsString();
1032-
1031+
JsonObject requestBody = gson.fromJson(body, JsonObject.class); // Parse JSON request body
1032+
JsonObject query = requestBody.getAsJsonObject("query");
1033+
if (query != null) {
1034+
System.out.println("Reading from request body query:" + query.toString());
1035+
JsonElement idElement = query.get("id");
1036+
if (idElement != null) {
1037+
JsonArray idInQuery = query.get("id").getAsJsonArray();
1038+
if (idInQuery != null && idInQuery.size() > 0) {
1039+
String id = idInQuery.get(0).getAsString();
1040+
ctx.contentType("application/json");
1041+
Gson response = new Gson();
1042+
JsonObject jsonObject = new JsonObject();
1043+
jsonObject.addProperty("userId", id);
1044+
ctx.result(response.toJson(jsonObject));
1045+
return;
1046+
}
10331047
}
1034-
1035-
return;
10361048
} else {
1037-
ctx.status(401).text("missing user id");
1038-
1049+
System.out.println("No query found from request body.");
10391050
}
1051+
ctx.status(401).result("missing user id");
10401052
} else if ("azure.webpubsub.sys.connected".equals(event)) {
10411053
String id = ctx.header("ce-userId");
10421054
System.out.println(id + " connected.");
@@ -1057,7 +1069,7 @@ Now let's handle the system `connect` event, which should contain the header `ce
10571069
```python
10581070
@app.route('/eventhandler', methods=['POST', 'OPTIONS'])
10591071
def handle_event():
1060-
if request.method == 'OPTIONS':
1072+
if request.method == 'OPTIONS' or request.method == 'GET':
10611073
if request.headers.get('WebHook-Request-Origin'):
10621074
res = Response()
10631075
res.headers['WebHook-Allowed-Origin'] = '*'
@@ -1066,25 +1078,29 @@ def handle_event():
10661078
elif request.method == 'POST':
10671079
user_id = request.headers.get('ce-userid')
10681080
type = request.headers.get('ce-type')
1081+
print("Received event of type:", type)
1082+
# Sample connect logic if connect event handler is configured
10691083
if type == 'azure.webpubsub.sys.connect':
1070-
print(f"{user_id} connected")
1071-
return '', 204
1084+
body = request.data.decode('utf-8')
1085+
print("Reading from connect request body...")
1086+
query = json.loads(body)['query']
1087+
print("Reading from request body query:", query)
1088+
id_element = query.get('id')
1089+
user_id = id_element[0] if id_element else None
1090+
if user_id:
1091+
return {'userId': user_id}, 200
1092+
return 'missing user id', 401
10721093
elif type == 'azure.webpubsub.sys.connected':
1073-
print(f"{user_id} connected")
1074-
return '', 204
1094+
return user_id + ' connected', 200
10751095
elif type == 'azure.webpubsub.user.message':
1076-
# default uses JSON
1077-
service.send_to_all(message={
1096+
service.send_to_all(content_type="application/json", message={
10781097
'from': user_id,
10791098
'message': request.data.decode('UTF-8')
10801099
})
1081-
# returned message is also received by the client
1082-
return {
1083-
'from': "system",
1084-
'message': "message handled by server"
1085-
}, 200
1100+
return Response(status=204, content_type='text/plain')
10861101
else:
10871102
return 'Bad Request', 400
1103+
10881104
```
10891105
10901106
---
@@ -1101,6 +1117,7 @@ Now let's update the web page to direct connect to Web PubSub service. One thing
11011117
<div id="messages"></div>
11021118
<script>
11031119
(async function () {
1120+
// sample host: mock.webpubsub.azure.com
11041121
let hostname = "<the host name of your service>";
11051122
let id = prompt('Please input your user name');
11061123
let ws = new WebSocket(`wss://${hostname}/client/hubs/Sample_ChatApp?id=${id}`);

0 commit comments

Comments
 (0)