Java Reference
In-Depth Information
@Override
public String encode(Object object) throws
EncodeException {
return gson.toJson(object); [2]
}
}
First, we create an instance of GSON in the init method; this action will be executed
when the endpoint is created. Next, in the encode method, which is called every time,
we send an object through an endpoint. We use JSON command to create JSON from an
object. This is quite concise when we think how reusable this little class is. If you want
more control on the JSON generation process, you can use the GsonBuilder class to
configure the Gson object before creation. We have the encoder in place. Now it's time to
alter our endpoint:
@ServerEndpoint(value = "/tickets",
encoders={JSONEncoder.class})[1]
public class TicketEndpoint {
@Inject
private SessionRegistry sessionRegistry;
@OnOpen
public void open(Session session, EndpointConfig conf) {
sessionRegistry.add(session);
}
@OnClose
public void close(Session session, CloseReason reason) {
sessionRegistry.remove(session);
}
public void send(@Observes Seat seat) {
sessionRegistry.getAll().forEach(session ->
session.getAsyncRemote().sendObject(seat)); [2]
}
}
Search WWH ::




Custom Search