javaandroidnode.jshttppersistent-connection

Persistent HTTP-connection from Android to Node.js server


I'm trying to implement a little communication scheme handling HTTP-requests from an Android device to a Node.js server. With the current code the Android side closes the connection after receiving the response from the 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;
}

Node:

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);

Further the connection event on the Node side is never called, every request is directly piped into the data event.

Is there a way to establish a persistent HTTP-connection such that the Node server can keep track of it while the connection is running until the Android side closes it again?


Solution

  • Socket.io seems to be a reasonable library to achieve persistent connections from Android to a Node.js server.