Pass a parameter to @OnOpen

You’re a programmer using cutting-edge techniques to achieve your goal, to code the next big thing.

Probably you’re using websocket, and have the support of  the brand new Java API for Websocket available now in your preferred JEE7 application server.

You  may want to send a parameter right away the connection is opened, instead of sending it  in a  message later.  Reviewing the spec. we find that OnOpen can take the following parameters:

  • optional Session
  • optional EndpointConfig
  • Zero to n String parameters annotated 

Great , that is just what we need.  See the following example

@ServerEndpoint(value= "/test/{name}")
public class WSocketService {
     private String socketName;
     @OnOpen
     public void open(@PathParam("name") String name) {
          // save the parameter into a instance variable
          socketName = name;
     }
}

from javascript ,  we would make the call like this to set the parameter to leo

connection = new WebSocket('ws://localhost:8080/App/test/leo');