CometD публикует сообщение обратно клиенту - PullRequest
2 голосов
/ 15 декабря 2011

У меня проблема с отправкой сообщения клиенту.Ниже мой код

JavaScript

dojox.cometd.publish('/service/getservice', {
                        userid : _USERID,

                    });
dojox.cometd.subscribe('/service/getservice', function(
            message) {
        alert("abc");
        alert(message.data.test);
    });

Configuration Servlet

bayeux.createIfAbsent("/service/getservice", new ConfigurableServerChannel.Initializer() {

        @Override
        public void configureChannel(ConfigurableServerChannel channel) {
            channel.setPersistent(true);
            GetListener channelListner = new GetListener();
            channel.addListener(channelListner);
        }
    });

класс GetListener

public class GetListener implements MessageListener {
 public boolean onMessage(ServerSession ss, ServerChannel sc) {
      SomeClassFunction fun = new SomeClassFunction;
}
}

SomeClassFunction

class SomeClassFunction(){

}

здесь я создаю логическую переменную логического успеха;если это правда, отправьте сообщение клиенту, который находится в JavaScript.как отправить сообщение обратно клиенту.Я также пробовал эту строку.

      remote.deliver(getServerSession(), "/service/getservice",
                    message, null);

, но она выдает ошибку на удаленном объекте и методе getServerSession.

1 Ответ

3 голосов
/ 15 декабря 2011

Чтобы достичь своей цели, вам не нужно ни реализовывать слушателей, ни настраивать каналы.Возможно, вам потребуется добавить некоторую конфигурацию на более позднем этапе, например, чтобы добавить авторизаторы.

Это код для ConfigurationServlet, взятый из этой ссылки :

public class ConfigurationServlet extends GenericServlet
{
    public void init() throws ServletException
    {
        // Grab the Bayeux object
        BayeuxServer bayeux = (BayeuxServer)getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
        new EchoService(bayeux);
        // Create other services here

        // This is also the place where you can configure the Bayeux object
        // by adding extensions or specifying a SecurityPolicy
    }

    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
    {
        throw new ServletException();
    }
}

Это код класса EchoService, взятый по этой ссылке :

public class EchoService extends AbstractService
{
    public EchoService(BayeuxServer bayeuxServer)
    {
        super(bayeuxServer, "echo");
        addService("/echo", "processEcho");
    }

    public void processEcho(ServerSession remote, Map<String, Object> data)
    {
        // if you want to echo the message to the client that sent the message
        remote.deliver(getServerSession(), "/echo", data, null);

        // if you want to send the message to all the subscribers of the "/myChannel" channel
        getBayeux().createIfAbsent("/myChannel");
        getBayeux().getChannel("/myChannel").publish(getServerSession(), data, null);
    }
}
...