Tutorial: Create a chat app with Azure Web PubSub service
Straipsnis
In Publish and subscribe message tutorial, you learn the basics of publishing and subscribing messages with Azure Web PubSub. In this tutorial, you learn the event system of Azure Web PubSub and use it to build a complete web application with real-time communication functionality.
In this tutorial, you learn how to:
Create a Web PubSub service instance
Configure event handler settings for Azure Web PubSub
Hanlde events in the app server and build a real-time chat app
If you prefer to run CLI reference commands locally, install the Azure CLI. If you're running on Windows or macOS, consider running Azure CLI in a Docker container. For more information, see How to run the Azure CLI in a Docker container.
If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For other sign-in options, see Sign in with the Azure CLI.
When you're prompted, install the Azure CLI extension on first use. For more information about extensions, see Use extensions with the Azure CLI.
Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.
This setup requires version 2.22.0 or higher of the Azure CLI. If using Azure Cloud Shell, the latest version is already installed.
Create an Azure Web PubSub instance
Create a resource group
A resource group is a logical container into which Azure resources are deployed and managed. Use the az group create command to create a resource group named myResourceGroup in the eastus location.
az group create --name myResourceGroup --location EastUS
Create a Web PubSub instance
Run az extension add to install or upgrade the webpubsub extension to the current version.
az extension add --upgrade --name webpubsub
Use the Azure CLI az webpubsub create command to create a Web PubSub in the resource group you've created. The following command creates a Free Web PubSub resource under resource group myResourceGroup in EastUS:
Important
Each Web PubSub resource must have a unique name. Replace <your-unique-resource-name> with the name of your Web PubSub in the following examples.
The output of this command shows properties of the newly created resource. Take note of the two properties listed below:
Resource Name: The name you provided to the --name parameter above.
hostName: In the example, the host name is <your-unique-resource-name>.webpubsub.azure.com/.
At this point, your Azure account is the only one authorized to perform any operations on this new resource.
Get the ConnectionString for future use
Important
A connection string includes the authorization information required for your application to access Azure Web PubSub service. The access key inside the connection string is similar to a root password for your service. In production environments, always be careful to protect your access keys. Use Azure Key Vault to manage and rotate your keys securely. Avoid distributing access keys to other users, hard-coding them, or saving them anywhere in plain text that is accessible to others. Rotate your keys if you believe they may have been compromised.
Use the Azure CLI az webpubsub key command to get the ConnectionString of the service. Replace the <your-unique-resource-name> placeholder with the name of your Azure Web PubSub instance.
az webpubsub key show --resource-group myResourceGroup --name <your-unique-resource-name> --query primaryConnectionString --output tsv
Copy the connection string to use later.
Copy the fetched ConnectionString and set it into environment variable WebPubSubConnectionString, which the tutorial later reads. Replace <connection-string> below with the ConnectionString you fetched.
In Azure Web PubSub, there are two roles, server and client. This concept is similar to the server and client roles in a web application. Server is responsible to manage the clients, listen, and respond to client messages. Client is responsible to send and receive user's messages from server and visualize them for end user.
In this tutorial, we build a real-time chat web application. In a real web application, server's responsibility also includes authenticating clients and serving static web pages for the application UI.
Navigate to the /src/main/java/com/webpubsub/tutorial directory. Open the App.java file in your editor. Use Javalin.create to serve static files:
package com.webpubsub.tutorial;
import io.javalin.Javalin;
public class App {
public static void main(String[] args) {
// start a server
Javalin app = Javalin.create(config -> {
config.staticFiles.add("public");
}).start(8080);
}
}
Depending on your setup, you might need to explicitly set the language level to Java 8. This step can be done in the pom.xml. Add the following snippet:
In the tutorial Publish and subscribe message, the subscriber consumes connection string directly. In a real world application, it isn't safe to share the connection string with any client, because connection string has high privilege to do any operation to the service. Now, let's have your server consuming the connection string, and exposing a negotiate endpoint for the client to get the full URL with access token. In such way, the server can add auth middleware before the negotiate endpoint to prevent unauthorized access.
Now let's add a /negotiate endpoint for the client to call to generate the token.
using Azure.Core;
using Microsoft.Azure.WebPubSub.AspNetCore;
using Microsoft.Azure.WebPubSub.Common;
using Microsoft.Extensions.Primitives;
// Read connection string from environment
var connectionString = Environment.GetEnvironmentVariable("WebPubSubConnectionString");
if (connectionString == null)
{
throw new ArgumentNullException(nameof(connectionString));
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddWebPubSub(o => o.ServiceEndpoint = new WebPubSubServiceEndpoint(connectionString))
.AddWebPubSubServiceClient<Sample_ChatApp>();
var app = builder.Build();
app.UseStaticFiles();
// return the Client Access URL with negotiate endpoint
app.MapGet("/negotiate", (WebPubSubServiceClient<Sample_ChatApp> service, HttpContext context) =>
{
var id = context.Request.Query["id"];
if (StringValues.IsNullOrEmpty(id))
{
context.Response.StatusCode = 400;
return null;
}
return new
{
url = service.GetClientAccessUri(userId: id).AbsoluteUri
};
});
app.Run();
sealed class Sample_ChatApp : WebPubSubHub
{
}
AddWebPubSubServiceClient<THub>() is used to inject the service client WebPubSubServiceClient<THub>, with which we can use in negotiation step to generate client connection token and in hub methods to invoke service REST APIs when hub events are triggered. This token generation code is similar to the one we used in the publish and subscribe message tutorial, except we pass one more argument (userId) when generating the token. User ID can be used to identify the identity of client so when you receive a message you know where the message is coming from.
The code reads connection string from environment variable WebPubSubConnectionString that we set in previous step.
Rerun the server using dotnet run --urls http://localhost:8080.
First install Azure Web PubSub SDK:
npm install --save @azure/web-pubsub
Now let's add a /negotiate API to generate the token.
const express = require('express');
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const app = express();
const hubName = 'Sample_ChatApp';
let serviceClient = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hubName);
app.get('/negotiate', async (req, res) => {
let id = req.query.id;
if (!id) {
res.status(400).send('missing user id');
return;
}
let token = await serviceClient.getClientAccessToken({ userId: id });
res.json({
url: token.url
});
});
app.use(express.static('public'));
app.listen(8080, () => console.log('server started'));
This token generation code is similar to the one we used in the publish and subscribe message tutorial, except we pass one more argument (userId) when generating the token. User ID can be used to identify the identity of client so when you receive a message you know where the message is coming from.
The code reads connection string from environment variable WebPubSubConnectionString that we set in previous step.
Rerun the server by running node server.
First add Azure Web PubSub SDK dependency and gson into the dependencies node of pom.xml:
Now let's add a /negotiate API to the App.java file to generate the token:
package com.webpubsub.tutorial;
import com.azure.messaging.webpubsub.WebPubSubServiceClient;
import com.azure.messaging.webpubsub.WebPubSubServiceClientBuilder;
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.javalin.Javalin;
public class App {
public static void main(String[] args) {
String connectionString = System.getenv("WebPubSubConnectionString");
if (connectionString == null) {
System.out.println("Please set the environment variable WebPubSubConnectionString");
return;
}
// create the service client
WebPubSubServiceClient service = new WebPubSubServiceClientBuilder()
.connectionString(connectionString)
.hub("Sample_ChatApp")
.buildClient();
// start a server
Javalin app = Javalin.create(config -> {
config.staticFiles.add("public");
}).start(8080);
// Handle the negotiate request and return the token to the client
app.get("/negotiate", ctx -> {
String id = ctx.queryParam("id");
if (id == null) {
ctx.status(400);
ctx.result("missing user id");
return;
}
GetClientAccessTokenOptions option = new GetClientAccessTokenOptions();
option.setUserId(id);
WebPubSubClientAccessToken token = service.getClientAccessToken(option);
ctx.contentType("application/json");
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("url", token.getUrl());
String response = gson.toJson(jsonObject);
ctx.result(response);
return;
});
}
}
This token generation code is similar to the one we used in the publish and subscribe message tutorial, except we call setUserId method to set the user ID when generating the token. User ID can be used to identify the identity of client so when you receive a message you know where the message is coming from.
The code reads connection string from environment variable WebPubSubConnectionString that we set in previous step.
Now let's add a /negotiate API to the server to generate the token.
import os
from flask import (
Flask,
request,
send_from_directory,
)
from azure.messaging.webpubsubservice import (
WebPubSubServiceClient
)
hub_name = 'Sample_ChatApp'
connection_string = os.environ.get('WebPubSubConnectionString')
app = Flask(__name__)
service = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
@app.route('/<path:filename>')
def index(filename):
return send_from_directory('public', filename)
@app.route('/negotiate')
def negotiate():
id = request.args.get('id')
if not id:
return 'missing user id', 400
token = service.get_client_access_token(user_id=id)
return {
'url': token['url']
}, 200
if __name__ == '__main__':
app.run(port=8080)
This token generation code is similar to the one we used in the publish and subscribe message tutorial, except we pass one more argument (user_id) when generating the token. User ID can be used to identify the identity of client so when you receive a message you know where the message is coming from.
The code reads connection string from environment variable WebPubSubConnectionString that we set in previous step.
Rerun the server using python server.py.
You can test this API by accessing http://localhost:8080/negotiate?id=user1 and it gives you the full url of the Azure Web PubSub with an access token.
Handle events
In Azure Web PubSub, when there are certain activities happen at client side (for example a client is connecting, connected, disconnected, or a client is sending messages), service sends notifications to server so it can react to these events.
Events are delivered to server in the form of Webhook. Webhook is served and exposed by the application server and registered at the Azure Web PubSub service side. The service invokes the webhooks whenever an event happens.
Azure Web PubSub follows CloudEvents to describe the event data.
Below we handle connected system events when a client is connected and handle message user events when a client is sending messages to build the chat app.
The Web PubSub SDK for AspNetCore Microsoft.Azure.WebPubSub.AspNetCore we installed in previous step could also help parse and process the CloudEvents requests.
First, add event handlers before app.Run(). Specify the endpoint path for the events, let's say /eventhandler.
Now, inside the class Sample_ChatApp we created in previous step, add a constructor to work with WebPubSubServiceClient<Sample_ChatApp> that we use to invoke the Web PubSub service. And OnConnectedAsync() to respond when connected event is triggered, OnMessageReceivedAsync() to handle messages from the client.
sealed class Sample_ChatApp : WebPubSubHub
{
private readonly WebPubSubServiceClient<Sample_ChatApp> _serviceClient;
public Sample_ChatApp(WebPubSubServiceClient<Sample_ChatApp> serviceClient)
{
_serviceClient = serviceClient;
}
public override async Task OnConnectedAsync(ConnectedEventRequest request)
{
Console.WriteLine($"[SYSTEM] {request.ConnectionContext.UserId} joined.");
}
public override async ValueTask<UserEventResponse> OnMessageReceivedAsync(UserEventRequest request, CancellationToken cancellationToken)
{
await _serviceClient.SendToAllAsync(RequestContent.Create(
new
{
from = request.ConnectionContext.UserId,
message = request.Data.ToString()
}),
ContentType.ApplicationJson);
return new UserEventResponse();
}
}
In the above code, we use the service client to broadcast a notification message in JSON format to all of whom is joined with SendToAllAsync.
Web PubSub SDK for express @azure/web-pubsub-express helps parse and process the CloudEvents requests.
npm install --save @azure/web-pubsub-express
Update server.js with the following code to expose a REST API at /eventhandler (which is done by the express middleware provided by Web PubSub SDK) to handle the client connected event:
const express = require("express");
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const app = express();
const hubName = "Sample_ChatApp";
let serviceClient = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hubName);
let handler = new WebPubSubEventHandler(hubName, {
path: "/eventhandler",
onConnected: async (req) => {
console.log(`${req.context.userId} connected`);
},
handleUserEvent: async (req, res) => {
if (req.context.eventName === "message")
await serviceClient.sendToAll({
from: req.context.userId,
message: req.data,
});
res.success();
},
});
app.get("/negotiate", async (req, res) => {
let id = req.query.id;
if (!id) {
res.status(400).send("missing user id");
return;
}
let token = await serviceClient.getClientAccessToken({ userId: id });
res.json({
url: token.url,
});
});
app.use(express.static("public"));
app.use(handler.getMiddleware());
app.listen(8080, () => console.log("server started"));
In the above code, onConnected simply prints a message to console when a client is connected. You can see we use req.context.userId so we can see the identity of the connected client. And handleUserEvent is invoked when a client sends a message. It uses WebPubSubServiceClient.sendToAll() to broadcast the message in a JSON object to all clients. You can see handleUserEvent also has a res object where you can send message back to the event sender. Here we simply call res.success() to make the WebHook return 200 (note this call is required even you don't want to return anything back to client, otherwise the WebHook never returns and client connection closes).
For now, you need to implement the event handler by your own in Java. The steps are straight forward following the protocol spec and illustrated in the below list:
Add HTTP handler for the event handler path, let's say /eventhandler.
First we'd like to handle the abuse protection OPTIONS requests, we check if the header contains WebHook-Request-Origin header, and we return the header WebHook-Allowed-Origin. For simplicity for demo purpose, we return * to allow all the origins.
Then we'd like to check if the incoming requests are the events we expect. Let's say we now care about the system connected event, which should contain the header ce-type as azure.webpubsub.sys.connected. We add the logic after abuse protection to broadcast the connected event to all clients so they can see who joined the chat room.
In the above code, we simply print a message to console when a client is connected. You can see we use ctx.header("ce-userId") so we can see the identity of the connected client.
The ce-type of message event is always azure.webpubsub.user.message. Details see Event message. We update the logic to handle messages that when a message comes in we broadcast the message in JSON format to all the connected clients.
// handle events: https://learn.microsoft.com/azure/azure-web-pubsub/reference-cloud-events#events
app.post("/eventhandler", ctx -> {
String event = ctx.header("ce-type");
if ("azure.webpubsub.sys.connected".equals(event)) {
String id = ctx.header("ce-userId");
System.out.println(id + " connected.");
} else if ("azure.webpubsub.user.message".equals(event)) {
String id = ctx.header("ce-userId");
String message = ctx.body();
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("from", id);
jsonObject.addProperty("message", message);
String messageToSend = gson.toJson(jsonObject);
service.sendToAll(messageToSend, WebPubSubContentType.APPLICATION_JSON);
}
ctx.status(200);
});
For now, you need to implement the event handler by your own in Python. The steps are straight forward following the protocol spec and are illustrated in the below list:
Add HTTP handler for the event handler path, let's say /eventhandler.
First we'd like to handle the abuse protection OPTIONS requests, we check if the header contains WebHook-Request-Origin header, and we return the header WebHook-Allowed-Origin. For simplicity for demo purpose, we return * to allow all the origins.
# validation: https://learn.microsoft.com/azure/azure-web-pubsub/reference-cloud-events#protection
@app.route('/eventhandler', methods=['OPTIONS'])
def handle_event():
if request.method == 'OPTIONS':
if request.headers.get('WebHook-Request-Origin'):
res = Response()
res.headers['WebHook-Allowed-Origin'] = '*'
res.status_code = 200
return res
Then we'd like to check if the incoming requests are the events we expect. Let's say we now care about the system connected event, which should contain the header ce-type as azure.webpubsub.sys.connected. We add the logic after abuse protection:
In the above code, we simply print a message to console when a client is connected. You can see we use request.headers.get('ce-userid') so we can see the identity of the connected client.
The ce-type of message event is always azure.webpubsub.user.message. Details see Event message. We update the logic to handle messages that when a message comes in we broadcast the message to all the connected clients.
@app.route('/eventhandler', methods=['POST', 'OPTIONS'])
def handle_event():
if request.method == 'OPTIONS':
if request.headers.get('WebHook-Request-Origin'):
res = Response()
res.headers['WebHook-Allowed-Origin'] = '*'
res.status_code = 200
return res
elif request.method == 'POST':
user_id = request.headers.get('ce-userid')
type = request.headers.get('ce-type')
if type == 'azure.webpubsub.sys.connected':
print(f"{user_id} connected")
return '', 204
elif type == 'azure.webpubsub.user.message':
# default uses JSON
service.send_to_all(message={
'from': user_id,
'message': request.data.decode('UTF-8')
})
# returned message is also received by the client
return {
'from': "system",
'message': "message handled by server"
}, 200
else:
return 'Bad Request', 400
Update the web page
Now let's update index.html to add the logic to connect, send message, and display received messages in the page.
<html>
<body>
<h1>Azure Web PubSub Chat</h1>
<input id="message" placeholder="Type to chat...">
<div id="messages"></div>
<script>
(async function () {
let id = prompt('Please input your user name');
let res = await fetch(`/negotiate?id=${id}`);
let data = await res.json();
let ws = new WebSocket(data.url);
ws.onopen = () => console.log('connected');
let messages = document.querySelector('#messages');
ws.onmessage = event => {
let m = document.createElement('p');
let data = JSON.parse(event.data);
m.innerText = `[${data.type || ''}${data.from || ''}] ${data.message}`;
messages.appendChild(m);
};
let message = document.querySelector('#message');
message.addEventListener('keypress', e => {
if (e.charCode !== 13) return;
ws.send(message.value);
message.value = '';
});
})();
</script>
</body>
</html>
You can see in the above code we connect use the native WebSocket API in the browser, and use WebSocket.send() to send message and WebSocket.onmessage to listen to received messages.
You could also use Client SDKs to connect to the service, which empowers you with auto reconnect, error handling, and more.
There's now one step left for the chat to work. Let's configure what events we care about and where to send the events to in the Web PubSub service.
Set up the event handler
We set the event handler in the Web PubSub service to tell the service where to send the events to.
When the web server runs locally, how the Web PubSub service invokes the localhost if it have no internet accessible endpoint? There are usually two ways. One is to expose localhost to public using some general tunnel tool, and the other is to use awps-tunnel to tunnel the traffic from Web PubSub service through the tool to your local server.
In this section, we use Azure CLI to set the event handlers and use awps-tunnel to route traffic to localhost.
Configure hub settings
We set the URL template to use tunnel scheme so that Web PubSub routes messages through the awps-tunnel's tunnel connection. Event handlers can be set from either the portal or the CLI as described in this article, here we set it through CLI. Since we listen events in path /eventhandler as the previous step sets, we set the url template to tunnel:///eventhandler.
Use the Azure CLI az webpubsub hub create command to create the event handler settings for the Sample_ChatApp hub.
Important
Replace <your-unique-resource-name> with the name of your Web PubSub resource created from the previous steps.
The complete code sample of this tutorial can be found here.
Now run the server using python server.py.
The complete code sample of this tutorial can be found here.
Open http://localhost:8080/index.html. You can input your user name and start chatting.
Lazy Auth with connect event handler
In previous sections, we demonstrate how to use negotiate 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.
Now let's use connect event handler to acheive the similar as what the negotiate section does.
Update hub settings
First let's update hub settings to also include connect event handler, we need to also allow anonymous connect so that clients without JWT access token can connect to the service.
Use the Azure CLI az webpubsub hub update command to create the event handler settings for the Sample_ChatApp hub.
Important
Replace <your-unique-resource-name> with the name of your Web PubSub resource created from the previous steps.
Now let's update upstream logic to handle connect event. We could also remove the negotiate endpoint now.
As similar to what we do in negotiate endpoint as demo purpose, we also read id from the query parameters. In connect event, the original client query is preserved in connect event requet body.
Now let's add the logic to handle the connect event azure.webpubsub.sys.connect:
// validation: https://learn.microsoft.com/azure/azure-web-pubsub/reference-cloud-events#protection
app.options("/eventhandler", ctx -> {
ctx.header("WebHook-Allowed-Origin", "*");
});
// handle events: https://learn.microsoft.com/azure/azure-web-pubsub/reference-cloud-events#connect
app.post("/eventhandler", ctx -> {
String event = ctx.header("ce-type");
if ("azure.webpubsub.sys.connect".equals(event)) {
String body = ctx.body();
System.out.println("Reading from request body...");
Gson gson = new Gson();
JsonObject requestBody = gson.fromJson(body, JsonObject.class); // Parse JSON request body
JsonObject query = requestBody.getAsJsonObject("query");
if (query != null) {
System.out.println("Reading from request body query:" + query.toString());
JsonElement idElement = query.get("id");
if (idElement != null) {
JsonArray idInQuery = query.get("id").getAsJsonArray();
if (idInQuery != null && idInQuery.size() > 0) {
String id = idInQuery.get(0).getAsString();
ctx.contentType("application/json");
Gson response = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("userId", id);
ctx.result(response.toJson(jsonObject));
return;
}
}
} else {
System.out.println("No query found from request body.");
}
ctx.status(401).result("missing user id");
} else if ("azure.webpubsub.sys.connected".equals(event)) {
String id = ctx.header("ce-userId");
System.out.println(id + " connected.");
ctx.status(200);
} else if ("azure.webpubsub.user.message".equals(event)) {
String id = ctx.header("ce-userId");
String message = ctx.body();
service.sendToAll(String.format("{\"from\":\"%s\",\"message\":\"%s\"}", id, message), WebPubSubContentType.APPLICATION_JSON);
ctx.status(200);
}
});
Now let's handle the system connect event, which should contain the header ce-type as azure.webpubsub.sys.connect. We add the logic after abuse protection:
@app.route('/eventhandler', methods=['POST', 'OPTIONS'])
def handle_event():
if request.method == 'OPTIONS' or request.method == 'GET':
if request.headers.get('WebHook-Request-Origin'):
res = Response()
res.headers['WebHook-Allowed-Origin'] = '*'
res.status_code = 200
return res
elif request.method == 'POST':
user_id = request.headers.get('ce-userid')
type = request.headers.get('ce-type')
print("Received event of type:", type)
# Sample connect logic if connect event handler is configured
if type == 'azure.webpubsub.sys.connect':
body = request.data.decode('utf-8')
print("Reading from connect request body...")
query = json.loads(body)['query']
print("Reading from request body query:", query)
id_element = query.get('id')
user_id = id_element[0] if id_element else None
if user_id:
return {'userId': user_id}, 200
return 'missing user id', 401
elif type == 'azure.webpubsub.sys.connected':
return user_id + ' connected', 200
elif type == 'azure.webpubsub.user.message':
service.send_to_all(content_type="application/json", message={
'from': user_id,
'message': request.data.decode('UTF-8')
})
return Response(status=204, content_type='text/plain')
else:
return 'Bad Request', 400
Update index.html to direct connect
Now let's update the web page to direct connect to Web PubSub service. One thing to mention is that now for demo purpose the Web PubSub service endpoint is hard-coded into the client code, please update the service hostname <the host name of your service> in the below html with the value from your own service. It might be still useful to fetch the Web PubSub service endpoint value from your server, it gives you more flexibility and controllability to where the client connects to.
<html>
<body>
<h1>Azure Web PubSub Chat</h1>
<input id="message" placeholder="Type to chat...">
<div id="messages"></div>
<script>
(async function () {
// sample host: mock.webpubsub.azure.com
let hostname = "<the host name of your service>";
let id = prompt('Please input your user name');
let ws = new WebSocket(`wss://${hostname}/client/hubs/Sample_ChatApp?id=${id}`);
ws.onopen = () => console.log('connected');
let messages = document.querySelector('#messages');
ws.onmessage = event => {
let m = document.createElement('p');
let data = JSON.parse(event.data);
m.innerText = `[${data.type || ''}${data.from || ''}] ${data.message}`;
messages.appendChild(m);
};
let message = document.querySelector('#message');
message.addEventListener('keypress', e => {
if (e.charCode !== 13) return;
ws.send(message.value);
message.value = '';
});
})();
</script>
</body>
</html>