Websocket Channel

From Documentation
Revision as of 09:04, 24 June 2021 by Hawk (talk | contribs) (use syntaxhighlight (via JWB))


Employment/Purpose

[Since ZK 8]

ZK has supported a way to share the application data between a ZK application and a websocket application within the same session. Here we demonstrate how to use the Storage in a desktop scope to share the application data through the websocket channel.

Example

Websocket Server

 1 @ServerEndpoint(value ="/echo/",
 2 	configurator = ZKWebSocket.class)
 3 public class EchoServer {
 4 	@OnOpen
 5 	public void onOpen(Session session, EndpointConfig config) {
 6 		//since zk 8.6.4
 7 		ZKWebSocket.initZkDesktop(session, config);
 8 	}
 9 
10 	@OnMessage
11 	public void onMessage(String message, Session session){
12 		Storage<Integer> storage = ZKWebSocket.getDesktopStorage(session);
13 		if ("receive".equals(message)) {
14 			Integer count = storage.getItem("count");
15 			try {
16 				session.getBasicRemote().sendText("Received..." + count);
17 			} catch (Exception e) {
18 				e.printStackTrace();
19 			}
20 		} else {
21 			try {
22 				storage.setItem("count", Integer.parseInt(message));
23 				session.getBasicRemote().sendText("Sent..." + message);
24 			} catch (IOException ex) {
25 				ex.printStackTrace();
26 			}
27 		}
28 	}
29 	@OnClose
30 	public void onClose(Session session){
31 	}
32 
33 }

As you can see above, in line 2, we have to register a ZKWebSocket class into the configurator of the ServerEndpoint annotation. And in line 12 we can use the method of ZKWebSocket.getDesktopStorage(Session) to receive the data storage from a websocket session (the storage is a thread-safe implementation). Note that the websocket session must have a dtid value which is sent from client as follows.

1 // Create a new instance of the websocket
2 var webSocket = new WebSocket("ws://localhost:8080/zkwebsocket/echo/?dtid=" + zk.$('$win').desktop.uuid);

ZK Application

MVVM Example

1 <window id="win" apply="org.zkoss.bind.BindComposer"
2             viewModel="@id('vm') @init('org.zkoss.foo.ZKWebSocketViewModel')">
3         <groupbox title="ZK">
4             <hlayout>count: <label value="@load(vm.count)"/></hlayout>
5             <button label="add" onClick="@command('cmd')"/>
6         </groupbox>
7 </window>
 1 @ToServerCommand("update")
 2 public class ZKWebSocketViewModel {
 3 
 4 	private Integer count;
 5 
 6 	@Init
 7 	public void init(@ContextParam(ContextType.DESKTOP) Desktop desktop) {
 8 		count = 100;
 9 		syncToStorage(desktop);
10 	}
11 
12 	@Command
13 	@NotifyChange("count")
14 	public void cmd(@ContextParam(ContextType.DESKTOP) Desktop desktop) {
15 		count++;
16 		syncToStorage(desktop);
17 	}
18 
19 	@Command("update")
20 	@NotifyChange("count")
21 	public void doUpdate(@ContextParam(ContextType.DESKTOP) Desktop desktop) {
22 		count = desktop.<Integer>getStorage().getItem("count");
23 	}
24 
25 	private void syncToStorage(Desktop desktop) {
26 		Storage<Integer> desktopStorage = desktop.getStorage();
27 		desktopStorage.setItem("count", count);
28 	}
29 	public Integer getCount() {
30 		return count;
31 	}
32 }

As you can see above, in line 22 and 26, we can receive the data storage from the desktop object to share or update the application data into it, so that the websocket echo server can use or get the latest data from it or vice versa.

MVC Example

1 <window id="win" apply="org.zkoss.foo.ZKWebSocketComposer">
2         <groupbox title="ZK">
3             <hlayout>count: <label id="label" /></hlayout>
4             <button id="btn" label="add"/>
5         </groupbox>
6 </window>
 1 public class ZKWebSocketComposer extends SelectorComposer<Window> {
 2 	@Wire Label label;
 3 	@Wire Button btn;
 4 	private Integer count;
 5 
 6 	@Override public void doAfterCompose(Window comp) throws Exception {
 7 		super.doAfterCompose(comp);
 8 		count = 100;
 9 		label.setValue("100");
10 		syncToStorage();
11 	}
12 
13 	@Listen("onClick = #btn")
14 	public void doClick() {
15 		count++;
16 		label.setValue(String.valueOf(count));
17 		syncToStorage();
18 	}
19 
20 	private void syncToStorage() {
21 		getSelf().getDesktop().getStorage().setItem("count", count);
22 	}
23 
24 	@Command // this annotation is under the package of org.zkoss.zk.ui.annotation
25 	public void update() {
26 		count = getSelf().getDesktop().<Integer>getStorage().getItem("count");
27 		label.setValue(String.valueOf(count));
28 	}
29 }

As you can see above, in line 21 and 26, we can receive the data storage from the desktop object to share or update the application data into it, so that the websocket echo server can use or get the latest data from it or vice versa.

Note: in line 24 Command annotation has been added since the release of ZK 8.0.0, and it is used to receive a notification from client to server. For more details, please take a look at the #Communication section.

Communication

From Websocket server to ZK application

MVVM Example

Here is the MVVM way to send a command from client to server.

1 // Create a new instance of the websocket
2 var webSocket = new WebSocket("ws://localhost:8080/zkwebsocket/echo/?dtid=" + zk.$('$win').desktop.uuid);
3 
4 // receive a message from websocket, and notify ZK application to update the component data.
5 webSocket.onmessage = function(event) {
6     zkbind.$('$win').command('update'); // the update command has already declared in ZKWebSocketViewModel.java
7 };

MVC Example

Here is the MVC way to send a command from client to server.

1 // Create a new instance of the websocket
2 var webSocket = new WebSocket("ws://localhost:8080/zkwebsocket/echo/?dtid=" + zk.$('$win').desktop.uuid);
3 
4 // receive a message from websocket, and notify ZK application to update the component data.
5 webSocket.onmessage = function(event) {
6     zkservice.$('$win').command('update'); // the update command has already declared in ZKWebSocketComposer.java
7 };

Command Parameter Converter

MVVM Example

When a user triggers a command with some data from client to server, the data should be in a Map (or says Object) type. For example,

1 	zkbind.$('$win').command('update', {foo: 'myfoo', bar: {title: 'myBarTitle'}});

In the Java code

 1 	public static class Bar {
 2 		private String title;
 3 		public void setTitle(String title) { this.title = title; }
 4 		public String getTitle() { return title; }
 5 	}
 6 	@Command("update")
 7 	@NotifyChange("count")
 8 	public void doUpdate(@ContextParam(ContextType.DESKTOP) Desktop desktop, @BindingParam("foo") String myfoo, @BindingParam("bar") Bar mybar) {
 9 		count = desktop.<Integer>getStorage().getItem("count");
10 	}

As you can see above, the data will automatically be converted into a specific object type according to the method declaration.

Note: developer can implement a custom Converter and specify it into the ZK library properties.

MVC Example

When a user triggers a command with some data from client to server, the data should be in an array type in order. For example,

1 	zkservice.$('$win').command('update', [{foo: "myfoo"}, {bar: "mybar"}]); // the arguments should be in order within an array.

In the Java code

 1 ...
 2 	public static class MyFoo {
 3 		private String foo;
 4 		public void setFoo(String foo) { this.foo = foo;}
 5 		public String getFoo() { return this.foo;}
 6 	}
 7 
 8 	public static class MyBar {
 9 		// omitted
10 	}
11 
12 	@Command
13 	public void update(MyFoo foo, MyBar bar) {
14 	}
15 }

As you can see above, the data will automatically be converted into a specific object type according to the method declaration.

Note: developer can implement a custom Converter and specify it into the ZK library properties.




Last Update : 2021/06/24

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.