xmpp协议的使用

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

在android里面用的smack包其实叫做asmack,该包提供了两种不同的连接方式:socket和httpclient。该并且提供了很多操作xmpp协议的API,也方便各种不同自定义协议的扩展。我们不需要自己重新去定义一套接收机制来扩展新的协议,只需继承然后在类里处理自己的协议就可以了。而本文今天主要说两点,一点就是消息是如何接收的,另一点就是消息是如何通知事件的。总的思路1.使用socket连接服务器2.将XmlPullParser的数据源关联到socket的InputStream3.启动线程不断循环处理消息4.将接收到的消息解析xml处理封装好成一个Packet包5.将包广播给所有注册事件监听的类逐步击破(声明在看下面的文章时,最好先理解一下smack的使用,这样才能达到深入的理解)(谨记:上图只显示本文章解释所要用到的类和方法,减缩了一些跟本文主题无关的代码,只留一条贯穿着从建立连接到接收消息的线。)解析这块东西打算从最初的调用开始作为入口,抽丝剥茧,逐步揭开。1.PacketListenerpacketListener=newPacketListener(){@OverridepublicvoidprocessPacket(Packetpacket){System.out.println(Activity----processPacket+packet.toXML());}};PacketFilterpacketFilter=newPacketFilter(){@Overridepublicbooleanaccept(Packetpacket){System.out.println(Activity----accept+packet.toXML());returntrue;}};解释:创建包的监听以及包的过滤,当有消息到时就会广播到所有注册的监听,当然前提是要通过packetFilter的过滤。2.connection=newXMPPConnection();XMPPConnection在这构造函数里面主要配置ip地址和端口(super(newConnectionConfiguration(169.254.141.109,9991));)3.connection.addPacketListener(packetListener,packetFilter);connection.connect();注册监听,开始初始化连接。4.publicvoidconnect(){//Stablishestheconnection,readersandwritersconnectUsingConfiguration(config);}5.privatevoidconnectUsingConfiguration(ConnectionConfigurationconfig){Stringhost=config.getHost();intport=config.getPort();try{this.socket=newSocket(host,port);}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}initConnection();}通过之前设置的ip和端口,建立socket对象6.protectedvoidinitDebugger(){Class?debuggerClass=null;try{debuggerClass=Class.forName(com.simualteSmack.ConsoleDebugger);Constructor?constructor=debuggerClass.getConstructor(Connection.class,Writer.class,Reader.class);debugger=(SmackDebugger)constructor.newInstance(this,writer,reader);reader=debugger.getReader();}catch(ClassNotFoundExceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}catch(Exceptione){thrownewIllegalArgumentException(Can'tinitializetheconfigureddebugger!,e);}}privatevoidinitReaderAndWriter(){try{reader=newBufferedReader(newInputStreamReader(socket.getInputStream(),UTF-8));}catch(UnsupportedEncodingExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}initDebugger();}privatevoidinitConnection(){//SetthereaderandwriterinstancevariablesinitReaderAndWriter();packetReader=newPacketReader(this);addPacketListener(debugger.getReaderListener(),null);//Startthepacketreader.Thestartup()methodwillblockuntilwe//getanopeningstreampacketbackfromserver.packetReader.startup();}从三个方法可以看出,建立reader和writer的对象关联到socket的InputStream,实例化ConsoleDebugger,该类主要是打印出接收到的消息,给reader设置了一个消息的监听。接着建立PacketReader对象,并启动。PacketReader主要负责消息的处理和通知7.publicclassPacketReader{PrivateExecutorServicelistenerExecutor;privatebooleandone;PrivateXMPPConnectionconnection;PrivateXmlPullParserparser;PrivateThreadreaderThread;ProtectedPacketReader(finalXMPPConnectionconnection){this.connection=connection;this.init();}/***Initializesthereaderinordertobeused.Thereaderisinitialized*duringthefirstconnectionandwhenreconnectingduetoanabruptly*disconnection.*/protectedvoidinit(){done=false;readerThread=newThread(){publicvoidrun(){parsePackets(this);}};readerThread.setName(SmackPacketReader);readerThread.setDaemon(true);//createanexecutortodeliverincomingpacketstolisteners.//wewilluseasinglethreadwithanunboundedqueue.listenerExecutor=Executors.newSingleThreadExecutor(newThreadFactory(){@OverridepublicThreadnewThread(Runnabler){Threadthread=newThread(r,smacklistenerprocessor);thread.setDaemon(true);returnthread;}});resetParser();}/***Startsthepacketreaderthreadandreturnsonceaconnectiontothe*serverhasbeenestablished.Aconnectionwillbeattemptedforamaximum*offiveseconds.AnXMPPExceptionwillbethrowniftheconnectionfails.**/publicvoidstartup(){readerThread.start();}/***Shutsthepacketreaderdown.*/publicvoidshutdown(){done=true;//Shutdownthelistenerexecutor.listenerExecutor.shutdown();}privatevoidresetParser(){try{parser=XmlPullParserFactory.newInstance().newPullParser();parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,true);parser.setInput(connection.reader);}catch(XmlPullParserExceptionxppe){xppe.printStackTrace();}}/***Parsetop-levelpacketsinordertoprocessthemfurther.**@paramthread*thethreadthatisbeingusedbythereadertoparseincoming*packets.*/privatevoidparsePackets(Threadthread){try{InteventType=parser.getEventType();do{if(eventType==XmlPullParser.START_TAG){if(parser.getName().equals(message)){processPacket(PacketParserUtils.parseMessage(parser));}System.out.println(START_TAG);}elseif(eventType==XmlPullParser.END_TAG){System.out.println(END_TAG);}eventType=parser.next();}while(!done&&eventType!=XmlPullParser.END_DOCUMENT&&thread==readerThread);}catch(Exceptione){e.printStackTrace();if(!done){}}}privatevoidprocessPacket(Packetpacket){if(packet==null){return;}//Loopthroughallcollectorsandnotifytheappropriateones.for(PacketCollectorcollector:connection.getPacketCollectors()){collector.processPacket(packet);}//Delivertheincomingpackettolisteners.listenerExec

1 / 46
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功