I'm trying to implement a long polling server using Dropwizard 0.7.0 framework. I've been suggested to use jetty integration. After some googling, I got really confused by things like websockets, jetty continuation, cometd.
My question is, what are these things and which one should I choose? And any example is really appreciated!
Edited
Our server has many clients, including mobile (ios, android), pc and web. Is websocket only available in web browser?
Websocket is available in all the clients you have listed.
Usually frameworks like Atmoshphere handles downgrading to other types of transports (e.g. longpolling instead of websockets) and abstracting away the differences for you. Websockets is the standard for things that long-polling tries to solve - i.e. server side push.
I have done websockets on jetty for Dropwizard 0.7.0 - but have a read on the thread I have linked to in the DW google group.
See http://www.eclipse.org/jetty/documentation/9.0.6.v20130930/websockets.html
and https://groups.google.com/d/msg/dropwizard-user/doNCx_35urk/5PIvd8_NHIcJ
Basically you add a websocket-servlet to DW which negotiates a websocket session:
final ServletRegistration.Dynamic websocket = environment.servlets().addServlet(
"websocket",
new MyWebSocketServlet(
environment.getObjectMapper(),
environment.metrics(),
configuration.getKafkaConfig()
)
);
websocket.setAsyncSupported(true);
websocket.addMapping("/websocket/*");
And the websocket servlet:
public class MyWebSocketServlet extends WebSocketServlet{
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyWebSocketEndpoint.class);
}
}
And last is your endpoint which is instanciated by the jetty websocket libs:
@WebSocket
public class MyWebSocketEndpoint {
@OnWebSocketMessage
public void onMessage(Session session, String s) throws IOException {
session.getRemote().sendString("Returned; "+s);
}
}
If you want to follow the JSR-356 websockets standard you can use one of these two Dropwizard bundles:
- dropwizard-websocket-jee7-bundle
- dropwizard-websockets bundle
I wrote the second one in order to support also websockets metrics (count messages, open sessions, session duration statstics etc...).
Example:
<dependency>
<groupId>com.liveperson</groupId>
<artifactId>dropwizard-websocket</artifactId>
<version>XXX</version>
</dependency>
Then:
public void initialize(Bootstrap<Configuration> bootstrap) {
bootstrap.addBundle(new WebsocketBundle(AnnotatedEchoServer.class));
}
@Metered
@Timed
@ExceptionMetered
@ServerEndpoint("/annotated-ws")
public static class AnnotatedEchoServer {
@OnOpen
public void myOnOpen(final Session session) throws IOException {
session.getAsyncRemote().sendText("welcome");
}
@OnMessage
public void myOnMsg(final Session session, String message) {
session.getAsyncRemote().sendText(message.toUpperCase());
}
@OnClose
public void myOnClose(final Session session, CloseReason cr) {
}
}