Java Reference
In-Depth Information
@ServerEndpoint("/acmechat")
public class AcmeChatEndpoint {
/**
* Message receiver method
*
* @param message
* @return
*/
@OnMessage
public String messageReceiver(String message) {
System.out.println("Received message:" + message);
// Do something with message
return message;
}
@OnOpen
public void onOpen(Session session) {
System.out.println("onOpen: " + session.getId());
// Do something with session object
}
@OnClose
public void onClose(Session session) {
System.out.println(session.getId());
// Do something with session object
}
}
The WebSocket endpoint will be accessible to clients at the URL ws://localhost:8080/IntroToEE7/acmechat .
When a message is sent from a client to the endpoint, it is sent to the messageReceiver method, where is processed
accordingly. In this case, a simple String message is returned to the client. Note that the messageReceiver method
could have accepted a number of string-based parameters, as mentioned previously. For instance, to send a
messageId parameter to the endpoint, path of /acmechat/{messageId} could have been used, and the method would
then look as follows:
@OnMessage
public String messageReceiver(String message,
@PathParam("messageId") String messageId) {
System.out.println("Received message:" + message + messageId);
// Do something with message
return message;
}
To learn more regarding @PathParam , please see the online documeantation at
http://docs.oracle.com/javaee/7/api/javax/websocket/server/PathParam.html .
To implement a WebSocket endpoint without using annotations, extend javax.websocket.Endpoint . In such
a case, the endpoint implementation must override the onMessage method, and can optionally override onOpen
and onError . The following example class demonstrates a WebSocket endpoint using the interface implementation
approach.
 
Search WWH ::




Custom Search