2011-12-15 136 views
2

我在向客戶端發回消息時遇到問題。下面是我的代碼CometD發佈消息給客戶端

的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方法的錯誤。

回答

3

爲了達到您的目標,您不需要實現監聽器,也不需要配置通道。您可能需要在稍後階段添加一些配置,例如爲了添加授權人。

這是ConfigurationServlet代碼,從這個link採取:

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類的代碼,採取來回此link:我已經用這種方法做

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); 
    } 
} 
+0

perissf像以前一樣,它正在成功地將消息發送回客戶端。但我想在上述情況下。因爲如果我將使用echo類,它會在someClassFunction類之前調用​​,因爲我想在執行someClassFunction之後發送消息,所以你告訴我授權者的概念,然後我必須研究它。 – 2011-12-16 06:38:33