a WebSocket is a protocol that allows bidirectional communication between a client(running on a browser) and a server. It can have interesting applications such as push notifications and chat. As of HTML 5, WebSocket has been introduced as part of the standard javascript. WebSocket operation depends on the browser type and its version, but normally it is supported by all the modern browsers. In this example, we are going to wrap the WebSocket API using JsInterop, and then use it from a GWT app to send and receive messages from a Spring Boot based server.

The WebSocket wrapper

@JsType(isNative=true, namespace=JsPackage.GLOBAL)
public class WebSocket extends EventTarget {
	@JsProperty
	public Function onclose;
	@JsProperty
	public Function onerror;
	@JsProperty
	public Function onmessage;
	@JsProperty
	public Function onopen;
	@JsProperty
	public String url;
	@JsConstructor
	public WebSocket(String url){
	
	}
	@JsMethod
	public native void send(String data);
	
	@JsMethod
	public native void close();
}


The Server

Then we can initialize a WebSocket from our application:

    WebSocket socket = new WebSocket("ws://localhost:8082/gwidgets-ws");
		
		socket.onmessage = (evt) -> {
			   MessageEvent event = evt.cast();
			   DivElement div = DOM.createDiv().cast();
			   div.setInnerText(event.getData());
			   homePanel.appendChild(div);
			   notificationsToast.toggle();
			return evt;
		};
		
		socket.onopen = (evt) -> {  
			   GWT.log("socket open");
			return evt;
		};
		
		socket.onclose = (evt) -> {
			   GWT.log("socket closed");
			return evt;
		};

We have used lambdas for event handlers to take advantage of GWT 2.8.0 Java 8 capabilities. Finally, we have used Spring Boot, and Spring’s support for WebSockets to implement a server that sends a notification each 2 mins to our app, and also can receive messages and display them on the console.

Our WebSocket configuration looks like:

@Configuration
@EnableWebSocket
public class SocketConfig implements WebSocketConfigurer{	
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(handler(), "/gwidgets-ws").setAllowedOrigins("*");
	}
	
	@Bean
	public SocketHandler handler(){
		return new SocketHandler();
	}
}

The SocketHandler implementation can be found here.

and finally, we need to implement our scheduling module that sends a message every two minutes:

@Component
public class ScheduledTemplate {
   @Autowired
   SocketHandler socketHandler;

   @Scheduled(cron="0 0/2 * * * ?")
    public void publishUpdates(){
	   socketHandler.brodcastMessage("server notification " + LocalDateTime.now().toString());
    }
}

Full source code can be found here: https://github.com/zak905/gwt-websocket-spring