2016-10-19 83 views
0

我想實現一個小通信方案來處理從Android設備到Node.js服務器的HTTP請求。使用當前代碼,Android端在收到標題響應後關閉連接。從Android到Node.js服務器的持久HTTP連接

爪哇:

public String doInBackground(Void... params) { 
    URL url = new URL("http://" + mServer.getHost() + ":" + mServer.getPort() + "/" + mPath); 
    HttpURLConnection http = (HttpURLConnection) url.openConnection(); 
    http.setConnectTimeout(TIMEOUT); 
    http.setRequestMethod("POST"); 
    http.setDoOutput(true); 
    http.connect(); 

    OutputStream out = http.getOutputStream(); 
    OutputStreamWriter writer = new OutputStreamWriter(out); 
    writer.write(mJson); 
    writer.flush(); 
    writer.close(); 

    mResponseCode = http.getResponseCode(); 
    if (mResponseCode != 200) { 
     http.disconnect(); 
     return ""; 
    } 

    InputStreamReader in = new InputStreamReader(http.getInputStream()); 
    BufferedReader br = new BufferedReader(in); 

    char[] chars = new char[BUF_SIZE]; 
    int size = br.read(chars); 

    String response = new String(chars).substring(0, size); 
    //http.disconnect(); 
    return response; 
} 

節點:

this.socket = http.createServer((req, res) => { 

    req.on('data', (chunk) => { 
     this.log.info("DATA"); 
     obj = JSON.parse(chunk.toString()); 
    }); 

    req.on('close',() => { 
     this.log.info("CLOSE"); 
    }); 

    req.on('connection', (socket) => { 
     this.log.info("CONNECTION"); 
    }); 

    req.on('end',() => { 
     this.log.info("END");  
    }); 
}); 

this.socket.listen(this.port, this.host); 

此外節點上側的connection事件沒有被調用,每個請求被直接用管道輸送到data事件。

有沒有辦法建立一個持久的HTTP連接,以便節點服務器可以在連接運行時跟蹤它,直到Android端再次關閉它?

+0

服務器沒有辦法跟蹤正常http連接中的客戶端,因此我認爲,建立一個持久的HTTP連接並不是必需的(也可能是)。 – marcel

回答

1

Socket.io似乎是一個合理的庫,實現從Android到Node.js服務器的持久連接。

相關問題