Implementing long polling server using Dropwizard 0.7.0

守給你的承諾、 提交于 2019-12-01 01:54:40

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:

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) {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!