sourdesi
sourdesi

Reputation: 380

Send a stream of integers from Android app and receive it on Node.js express server

I'm going to try to make a simple hack that sends continually streaming integers from an Android App to a Node.js server.

I want to know how to create such a stream in Android and how to receive it in my Node.js server if I am using express for routing the API calls.

If anyone can give me a high level explanation of how this can work that would be great. Specific code examples of creating Node.js ReadStreams from an outside WriteStream would be even better.

Upvotes: 0

Views: 293

Answers (1)

qubyte
qubyte

Reputation: 17748

Depending on the frequency of the stream, you may want to consider websockets. There are android libraries available that implement the websocket standard (a quick search turned up https://github.com/koush/android-websockets), which claims to implement both websockets, and Socket.IO.

Conveniently, both websockets and Socket.IO are perfect for Node. I like the ws module the most for pure websockets. You can create a websocket server, and feed it an express app to let it handle websocket upgrade requests. Something along the lines of (not tested):

var express = require('express');
var websockets = require('ws')
var app = express();
var wsServer = new WebSocketServer({ noServer: true });

var server = app.listen(3000, function () {
    // Express stuff.
});

server.on('upgrade', function (req, sock, head) {
    wsServer.handleUpgrade(req, sock, head, function (connection) {
        // The connection object will deliver the stream.
        // You'll need to listen for 'message' events.
    });
});

wsServer.on('error', function (err) {
    // Don't forget errors.
});

For Socket.IO, see here.

Upvotes: 1

Related Questions