@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
}
Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial |
Previous | Next | Contents |
The following example shows how to create the same endpoint from Programmatic Endpoints using annotations instead:
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
}
The annotated endpoint is simpler than the equivalent programmatic
endpoint, and it is deployed automatically with the application to the
relative path defined in the ServerEndpoint
annotation. Instead of
having to create an additional class for the message handler, this
example uses the OnMessage
annotation to designate the method invoked
to handle messages.
Table 19-1 lists the annotations available in the
javax.websocket
package to designate the methods that handle lifecycle
events. The examples in the table show the most common parameters for
these methods. See the API reference for details on what combinations of
parameters are allowed in each case.
Table 19-1 WebSocket Endpoint Lifecycle Annotations
Annotation |
Event |
Example |
|
Connection opened |
|
|
Message received |
|
|
Connection error |
|
|
Connection closed |
|
Previous | Next | Contents |