title: Java WebSocket session resulting to null after onOpen
body: <p>I am using websockets for the first time on a javafx project, when I start the program the session is set to the local variable session, but after when I call the sendMessage function the session is back to null. Below please find my client class</p>
  
  <pre><code>package myclient;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.URI;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import javafx.application.Application;
  import javafx.fxml.FXMLLoader;
  import javafx.scene.Parent;
  import javafx.scene.Scene;
  import javafx.stage.Stage;
  import javax.websocket.ClientEndpoint;
  import javax.websocket.ContainerProvider;
  import javax.websocket.DeploymentException;
  import javax.websocket.OnClose;
  import javax.websocket.OnMessage;
  import javax.websocket.OnOpen;
  import javax.websocket.Session;
  import javax.websocket.WebSocketContainer;
  
  @ClientEndpoint
  public class Client extends Application {    
      private static final Logger LOGGER = Logger.getLogger(Client.class.getName());
      private Session session;
  
      @OnOpen
      public void onOpen(Session session){
          this.session = session;
          System.out.println("Opened Session " + this.session);
      }
  
      @OnClose
      public void onClose(){
          System.out.println("Closed Session " + this.session);
      }
  
      @OnMessage
      public void onMessage(String msg){
          System.out.println("Websocket message received! " + msg);   
      }
  
      @Override
      public void start(Stage stage) throws Exception {
          Parent root = FXMLLoader.load(getClass().getResource("FXMLClient.fxml"));
  
          Scene scene = new Scene(root);
  
          connectToWebSocket();
          stage.setScene(scene);
          stage.show();
      }
  
      private void connectToWebSocket() {
          System.out.println("Client WebSocket initialized&gt;&gt;  " + this.session);
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
          try {
              URI uri = URI.create("ws://localhost:8080/Server/endpoint");
              container.connectToServer(this, uri);
          } 
          catch (DeploymentException | IOException ex) {
              LOGGER.log(Level.SEVERE, null, ex);
              System.exit(-1);
          }
      }
  
      public void sendMessage(String message) throws IOException{
          if(this.session != null){
                  System.out.println(message + ", " + this.session);
                  this.session.getBasicRemote().sendText(message);
          }
          else {
              System.out.println("Session is null");
          }
      }
  
      public static void main(String[] args) {
          launch(args);        
      }
  
  }
  </code></pre>
  
  <p>Any suggestions?</p>
  
  <p>Thanks in advance</p>