CTE-4767 WebSockets in Canvas
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:
- Enable WEB_SOCKET_ENABLED=Y property in the securityconfig property file.
- Create instance for WebSocketManager in your application class file.
WebSocketManager webSocketManager=WebSocketManager.getInstance();
- Invoke the publishMessage method to publish the WebSocket from server to client.
// Input argument : WebSocketPublisherBean instance with properties publisherName, header, message
webSocketManager.publishMessage();
Sample: The following snippet publishes the custom message from WebSocket.
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.
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.
ct.comm.MessageBus.subscribe('monitor','ct.websocket.message.received',this,function(data){//business logic need to be done herealert('WELCOME TO WEBSOCKET'+data);});