Canvas offers WebSockets to achieve full-duplex communication channels over a single TCP connection. This helps you build communication protocol for a persistent, bi-directional, full duplex TCP connection from a user's web browser to a server.The Canvas WebSocket connection is initiated by sending a WebSocket handshake request from a browser's HTTP connection to a server to upgrade the connection.
In the scenario of updating a UI component of a website at frequent intervals (e.g. stock rates or train details), the WebSockets serve as optimal solution where multiple calls to the server can be made by establishing a single connection. This decreases the serving time of the requests.Steps to Publish and Subscribe to WebSockets:
...
Create instance for WebSocketManager in your application class file.
Code Block | ||
---|---|---|
| ||
WebSocketManager webSocketManager=WebSocketManager.getInstance(); |
Invoke the publishMessage method to publish the WebSocket from server to client.
Code Block | ||
---|---|---|
| ||
// Input argument : WebSocketPublisherBean instance with properties publisherName, header, message
webSocketManager.publishMessage(); |
...
Code Block | ||
---|---|---|
| ||
package com.intellectdesign.modelhouse.websocket;
import com.intellectdesign.canvas.websocket.WebSocketManager;
import com.intellectdesign.canvas.websocket.WebSocketPublisherBean;
import java.util.HashMap;
import java.util.Map;
public class WebSocketMessagePublisher {
public static void customPublish(String publisherName,Map header,Map Message){
WebSocketManager webSocketManager;
webSocketManager = WebSocketManager.getInstance();
WebSocketPublisherBean webSocketPublisherBean=new WebSocketPublisherBean();
webSocketPublisherBean.setPublisherName(publisherName);
webSocketPublisherBean.setHeader(header);
webSocketPublisherBean.setMessage(Message);
webSocketManager.publishMessage(webSocketPublisherBean);
}
public static void main(String[] args) {
Map headerData=new HashMap();
headerData.put("Test", "test1");
Map bodyData=new HashMap();
bodyData.put("data", "data1");
WebSocketMessagePublisher.customPublish("monitor",headerData,bodyData);
}
} |
Subscribe with WebSocket channel. For the first time, the connection will be established with namespace ct.websocket.message.received.
Code Block | ||
---|---|---|
| ||
ct.MessageBus.subscribe('subscribename','ct.websocket.message.received');
// subscribename => subscriber name
// ct.websocket.message.received => namespace and it will be always same |
Sample: The following snippet subscribe establish & fetch data from web socket connection.
...
language | java |
---|
...
For more information referĀ Web Sockets in Canvas.