項目中用到smack的長連接這塊關鍵有以下這幾個類: Connection , XMPPConnection , PakcetWriter , PacketReader. 如下圖:
查看XMPPConnection源碼:
- protected void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException {
- String host = config.getHost();
- int port = config.getPort();
- try {
- if (this.socket == null || this.socket.isClosed()) {
- LogUtil.i(TAG, "this.socket == null || this.socket.isClosed()");
- if (config.getSocketFactory() == null) {
- this.socket = new Socket(host, port);
- } else {
- this.socket = config.getSocketFactory().createSocket(host, port);
- }
- }
- private void initConnection() throws XMPPException {
- usingCompression = false;
- // Set the reader and writer instance variables
- initReaderAndWriter();
- try {
- // if (isFirstInitialization) {
- packetWriter = new PacketWriter(this);
- packetReader = new PacketReader(this);
- // If debugging is enabled, we should start the thread that will
- // listen for
- // all packets and then log them.
- if (config.isDebuggerEnabled()) {
- addPacketListener(debugger.getReaderListener(), null);
- if (debugger.getWriterListener() != null) {
- addPacketSendingListener(debugger.getWriterListener(), null);
- }
- }
- // } else {
- // packetWriter.init();
- // packetReader.init();
- // }
- // Start the packet writer. This will open a XMPP stream to the
- // server
- packetWriter.startup();
- // Start the packet reader. The startup() method will block until we
- // get an opening stream packet back from server.
- packetReader.startup();
- // Make note of the fact that we're now connected.
- connected = true;
以上執行順序是
1. initReaderAndWriter()方法通過上面創建的socket實例化connection
的Writer和Reader.
2. 實例化PacketWriter和PacketReader對象.
PacketWriter就是向服務器發送數據發送心跳包一直保持與服務器的連接連. PacketReader則是不斷的讀取並且解析服務器推送的消息.
3. 分別調用packetWriter和packetReader的startup()方法.
至此整個連接過程就建立完成了.
長連接大致流程基本就這樣, 也許還是一頭霧水.
1.終端如何發生心跳包與服務器一直保持聯繫的呢.
2.服務器推送消息到終端, 終端是如何根據消息進行分發處理的呢.