Java Reference
In-Depth Information
Examining the generated Java code
The following code snippet lists the Java source code for the generated WebSocket
server endpoint:
package org.glassfish.samples.websocket.echo;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
public class EchoEndpoint {
public String echo(String message) {
return message;
A Java class that processes WebSocket requests on the server side is called a server
endpoint. As we can see, developing a WebSocket server endpoint using the Java
API for WebSocket requires very little code.
We can designate a Java class as a server endpoint by annotating it with the
@ServerEndPoint annotation. Its value attribute indicates the Uniform Resource
Identifier (URI) of the server endpoint, and clients (typically client-side web
applications) access the server endpoint via this URI.
Any method annotated with the @OnMessage annotation is invoked automatically
any time a client sends a message to the WebSocket server endpoint. Methods
annotated with this annotation and expecting textual data must take a string
argument, which will contain the contents of the message sent from the client. The
contents of the message can be anything; however, it is a common practice for the
clients to send JSON-formatted data. In the NetBeans sample application, a simple
string is passed to the echo() method.
The value returned by the @OnMessage annotated method is sent back to the client.
A typical use case is to send a JSON-formatted string; however, in this simple
example, the string that was received as an argument is sent back to the client.
Search WWH ::

Custom Search