WebSocketOpenClose.java - Session Open and Close


How to provide call back methods for session open and close events with WebSocket API?

✍: FYIcenter.com


Adding session open and close event call back methods can be done with @OnOpen and @OnCLose annotated methods as shown below:

// Copyright (c) 2016 FYIcenter.com
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import javax.websocket.*;

public class WebSocketOpenClose {
   public static void main(String[] args) throws Exception {
      WebSocketContainer c = ContainerProvider.getWebSocketContainer();
	  URI u = new URI("wss://echo.websocket.org");
	  Session s = c.connectToServer(WebSocketOpenClose.class, u);

      System.out.println("WebSocket session info:");
      System.out.println("   Protocol version: "+s.getProtocolVersion());
      System.out.println("   Request URI: "+s.getRequestURI());

	  RemoteEndpoint.Basic r = s.getBasicRemote();
	  r.sendText("Hello there!");


   public void OnMessage(String message) {
      System.out.println("-- Message received: "+message);
   public void OnOpen(Session session) {
      System.out.println("-- Session started: "+session.getId());
   public void OnClose(Session session, CloseReason reason) {
      System.out.println("-- Session closed: "+session.getId()+" - "+reason);

You can compile and run the above example in a command window with Java SE JDK 8 and the tyrus-standalone-client.jar from Java EE 7 SDK:

   -cp \fyicenter\glassfish4\mq\lib\tyrus-standalone-client.jar 

   -cp .;\fyicenter\glassfish4\mq\lib\tyrus-standalone-client.jar 

-- Session started: fefe38df-30fe-40d3-a18a-2a1e4d5bbcfd
WebSocket session info:
   Protocol version: 13
   Request URI: wss://echo.websocket.org
-- Message received: Hello there!
-- Session closed: fefe38df-30fe-40d3-a18a-2a1e4d5bbcfd - CloseReason[1000]


Using WebSocket API in Java Programs

⇒⇒FAQ for WebSocket API

2018-01-16, 1063👍, 0💬