从 Android 到 Node.js 服务器的持久 HTTP-connection

Persistent HTTP-connection from Android to Node.js server

我正在尝试实现一个小的通信方案来处理从 Android 设备到 Node.js 服务器的 HTTP-requests。使用当前代码,Android 端在收到来自 header.

的响应后关闭连接

Java:

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-connection 以便节点服务器可以在连接 运行 时跟踪它,直到 Android 端再次关闭它?

Socket.io 似乎是实现从 Android 到 Node.js 服务器的持久连接的合理库。