The tutorial in this chapter will only cover the related content of room state management once. If you want to learn more about the relevant content, you can read 《Real-time Room State Management》 after reading this chapter.
Everything about the Netless interactive whiteboard is based on the room. The moment the room is created is the time to start the journey of the interactive whiteboard. In order to create a room, you need to prepare App Identifier and SDK Token.
App Idnetifier indicates which application the room belongs to. Application and enterprise account association. In this way, the room expenses can be linked to the corporate account.
The SDK Token is checked out by the application. With it, the Netless service determines that the operation of creating a room is authorized. You can read 《Project and Authority》 to learn how to obtain App Identifier and SDK Token.
After preparation, use the following code to call the API of the Netless service to create a room.
var url = "https://shunt-api.netless.link/v5/rooms";
var requestInit = {
method: "POST",
headers: {
"content-type": "application/json",
"token": sdkToken, // SDK Token issued must be prepared in advance
},
};
window.fetch(url, requestInit).then(function(response) {
return response.json();
}).then(function(roomJSON) {
// Create the room successfully, get the roomJSON describing the room information
console.log(roomJSON);
}).catch(function(err) {
// Failed, print out Error to analyze why it failed
console.error(err);
});
If the execution is successful, a real-time interactive room will be created. The Netless server will return a JSON object to describe the information of the newly created room. As expected, the contents of this JSON are as follows.
{
"uuid": "dcfc7fb09f6511eabc8da545523f6422",
"name": "",
"teamUUID": "34YtcH_MEeqFMjt5vcNozQ",
"isRecord": false,
"isBan": false,
"createdAt": "2020-05-26T15:30:43.706Z",
"limit": 0
}
Among them, uuid
is the most important field.
It is recommended to perform the room creation operation on the business server, not on the front end or the client. In order to demonstrate the complete process, this chapter uses the front-end window.fetch method to call the Netless server API. Do not emulate this behavior in formal web applications.
SDK Token is an important asset of the company and the team. In principle, it can only be generated and used in the business server. Absolutely not to die on the front end! Never transmit to the front end via the network! Otherwise, others can steal the SDK Token through decompilation, packet capture, etc. Once the SDK Token is leaked, it will cause serious security problems.
For more information about creating room API, please refer to 《Room | Server》.
Before joining the room, prepare the UUID and Room Token of the room. Among them, UUID is a string used to uniquely identify the room. The Room Token is used for authentication when joining a room.
You can check out the Room Token for a specific room by calling the server API method. Just like creating a room, this process also requires an SDK Token.
Actually, we have a better way to create Room Token. At this time, in order to save trouble, the front end initiates an HTTP request. But in the actual application development process, you should choose the most reasonable way to generate Room Token according to your own situation. For details, please refer to 《Checkout Token|Project and Permission》.
var uuid = "uuid of a specific room";
var url = "https://shunt-api.netless.link/v5/tokens/rooms/" + uuid;
var requestInit = {
method: "POST",
headers: {
"content-type": "application/json",
"token": sdkToken, // SDK Token issued must be prepared in advance
},
body: JSON.stringify({
"lifespan": 0, // indicates that the Room Token will never expire
"role": "admin", // indicates that Room Token has Admin authority
}),
};
window.fetch(url, requestInit).then(function(response) {
return response.json();
}).then(function(roomToken) {
// Successfully get the Room Token of the room
joinRoom(roomUUID, roomToken);
}).catch(function(err) {
console.error(err);
});
Room Token can only access the designated room, and its authority is weaker than that of SDK Token. It can be distributed to the front end according to business logic.
Since the Room Token must be checked out through the Netless server API, the SDK Token must be used for this behavior. Obviously, due to security concerns, this operation cannot be done on the front end.
When the front end needs the Room Token, the API of the business server should be called first, and then the business server calls the Netless server API to check out the Room Token.
For more information about the API for creating Room Token, please refer to 《Room | Server》.
After creating a real-time interactive room and obtaining the uuid
and roomToken
, you can use these two parameters to call the method on the front end to join the room.
Think about it, how should uuid and roomToken be passed to the front end? In fact, it depends on the business logic. You can communicate with the product managers in the team to design a reasonable way.
For example, first request the API of the business server to read the room list (each item contains the uuid of the room). When you click on one of the rooms, read the uuid in the item. And initiate a fetch request to call the API of the business server, let the server application use the SDK Token to check out the Room Token, and then return it to the front end.
First, create an instance of WhiteWebSdk
.
import {WhiteWebSdk} from "white-web-sdk";
var whiteWebSdk = new WhiteWebSdk({
appIdentifier: appIdentify, // Get App Identifier from the management console
});
We will use this whiteWebSdk
instance many times in the future. It is recommended to use it as a singleton global variable.
Then, join the room with the following code.
var joinRoomParams = {
uuid: uuid,
roomToken: roomToken,
};
whiteWebSdk.joinRoom(joinRoomParams).then(function(room) {
// Join the room successfully, get the room object
}).catch(function(err) {
// failed to join the room
console.error(err);
});
After successfully joining the room, you will get the room
object via callback. This is an important object, after which all our code will be written around it.
Now, let's display the interactive whiteboard on the web page. Before this, you need to prepare whiteboard placeholders in the Dom tree of the web page.
<div id="whiteboard" style="width: 100%; height: 100vh;"></div>
Then, display the whiteboard on the web page through the following code.
room.bindHtmlElement(document.getElementById("whiteboard"));
After that, you can use the mouse to draw lines on the web page. Sincerely, it means that you have successfully joined the room and successfully displayed the whiteboard. If not, you may have a problem.
First, it is necessary to determine whether the room is successfully added. You can first enter the Console page through the development mode of the browser to view the code output log. If you see error messages (the messages are often marked in bold red), then it is almost certain that the room has failed to join.
Read these error messages and analyze the possible causes. In fact, the reasons are as follows:
uuid
and roomToken
.On the contrary, if the Console does not report any error messages, it at least means that the room has been added successfully. Excluding the failure to join the room, let’s see if it’s a problem with the style display.
Enter the Elements page through the development mode of the browser and find the whiteboard placeholder <div>
. Take a look at its size. If any item of width and height is 0px
, you can be sure that there is a problem with the style.
In order to solve the style problem, you need to adjust the style arrangement in Dom, that is, adjust the style
attribute and class
attribute of <div>
until the size of the whiteboard placeholder <div>
meets expectations. This is what the front-end engineer has been doing in his work, I believe it is familiar to you.
If you use react
to manage web views, there is no need to set whiteboard placeholder <div>
. After successfully joining the room and getting the room
object, the interactive whiteboard can be displayed through the following code.
JavaScript
import React from "react";
import {RoomWhiteboard} from "white-react-sdk";
class App extends React.Component {
render() {
var style = {
width: "100%",
height: "100vh",
};
return <RoomWhiteboard room={room} style={style}/>;
}
}
TypeScript
import * as React from "react";
import {RoomWhiteboard} from "white-react-sdk";
class App extends React.Component {
public render(): React.ReactNode {
const style = {
width: "100%",
height: "100vh",
};
return <RoomWhiteboard room={room} style={style}/>;
}
}
Netless interactive whiteboard provides a special SDK for React projects:
white-react-sdk
. This SDK is a superset that can completely replacewhite-web-sdk
.
If you no longer use the whiteboard, you should leave the room. Netless interactive whiteboard will not leave the room automatically. For the following reasons, we should not miss the leave room
operation.
If the user closes the browser directly, or closes the current webpage Tab, the room will be released automatically, no need to worry.
The following code can actively leave the room. If the room is no longer needed, remember to call, otherwise the room will leak.
room.disconnect().then(function() {
// successfully left the room
}).catch(function(err) {
// Failed to leave the room, get an error err
});
If it is found that Netless has issued a higher-than-expected bill, it may be caused by a "room leak". At this moment, you can troubleshoot the business logic code of the application, or refactor those that may cause confusion in the state.
After thoroughly repairing the "room leak" problem, you will find that the bill starts to meet expectations.
In order to ensure that the application can run stably, exception process handling should be considered at the beginning of business process design. Imagine your web application is running on the browsers of millions of households. Network problems, DNS problems, and authentication problems of thousands of households are constantly emerging.
If the abnormal process is not handled, going online is a disaster. We strongly recommend that you take the exception process into consideration when designing your business logic. Netless interactive whiteboard provides a variety of ways for you to deal with the abnormal flow of the room in real time.
For example, both joinRoom
and disconnect
will return a Promise object. If you are not familiar with Promise objects, you can read 《Promise-JavaScript | MDN》 first.
If the asynchronous method fails, an error will be thrown. Intercept the error in the following way and enter the exception handling process.
room.disconnect().catch(function (err) {
// Intercept the error and enter the exception handling process
});
If your development environment supports await
syntax, you can write the code as follows.
try {
await room.disconnect();
} catch (err) {
// Intercept the error and enter the exception handling process
}
You can monitor the exception of the real-time room by attaching a callback function when joinRoom
.
var joinRoomParams = {
uuid: roomUUID,
roomToken: roomToken,
};
whiteWebSdk.joinRoom(joinRoomParams, {
onDisconnectWithError: function(err) {
// The room was disconnected from the server due to an error
},
onKickedWithReason: function(err) {
// User is kicked out of the room
},
});