问题描述
packagecom.sec.comet4j;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;importorg.comet4j.core.CometConnection;importorg.comet4j.core.CometContext;importorg.comet4j.core.CometEngine;importorg.comet4j.core.event.ConnectEvent;importorg.comet4j.core.listener.ConnectListener;publicclassHelloWorldextendsConnectListenerimplementsServletContextListener{privatestaticfinalStringCHANNEL="hello";Map<String,String>map=newHashMap<String,String>();;CometContextcometContext=CometContext.getInstance();publicvoidcontextInitialized(ServletContextEventarg0){CometContextcc=CometContext.getInstance();cc.registChannel(CHANNEL);ThreadhelloAppModule=newThread(newHelloAppModule(),"SenderAppModule");helloAppModule.setDaemon(true);CometEngineengine=cometContext.getEngine();engine.addConnectListener(newHelloWorld());helloAppModule.start();}classHelloAppModuleimplementsRunnable{CometEngineengine=cometContext.getEngine();publicvoidrun(){while(true){try{Thread.sleep(1000);}catch(Exceptionex){ex.printStackTrace();}Stringout=(String)cometContext.getServletContext().getAttribute("out");List<CometConnection>connections=engine.getConnections();System.out.println(map.size()+"集合的大小");engine.sendTo(CHANNEL,connections,"");engine.sendToAll(CHANNEL,out);if(connections.size()>=1){cometContext.getServletContext().removeAttribute("out");}}}}publicvoidcontextDestroyed(ServletContextEventarg0){}publicbooleanhandleEvent(ConnectEventarg0){System.out.println("进入监听器");//TODOAuto-generatedmethodstubSystem.out.println(cometContext.getServletContext().getAttribute("usersName"));System.out.println(arg0.getConn().getId());map.put((String)cometContext.getServletContext().getAttribute("usersName"),arg0.getConn().getId());(这里在后台已经拿到值了,在这也put进去了,但是在上边判断集合大小时总是为0,为啥呢)returntrue;}}