Sunday, March 2, 2014

Create TCP server using Node,js with net module, run on Raspberry Pi, connected with Android

This example create TCP server with Node.js using net module, run on Raspberry Pi. To test it with Android client side app, refer to the example at Android Server/Client example - client side using Socket.
Server side implemented with Node.js, run on Raspberry Pi.
Server side implemented with Node.js, run on Raspberry Pi.

Client side run on Android
Client side run on Android
When the Node.js program run, it list it's own IP address and assigned port, and wait for client. In client side running on Android, enter the server IP and port, and connect. When client connect to server, server side will send back a message and end the connection.


Node.js code in server side.
var os=require('os');
var net=require('net');

var networkInterfaces=os.networkInterfaces();

var port = 8081;
var count = 1;

function callback_server_connection(socket){
    var remoteAddress = socket.remoteAddress;
    var remotePort = socket.remotePort;
    socket.setNoDelay(true);
    console.log("connected: ", remoteAddress, " : ", remotePort);
    
    var msg = 'Hello ' + remoteAddress + ' : ' +  remotePort + '\r\n'
        + "You are #" + count + '\r\n';
    count++;

    socket.end(msg);
    
    socket.on('data', function (data) {
        console.log(data.toString());
    });
    
    socket.on('end', function () {
        console.log("ended: ", remoteAddress, " : ", remotePort);
    });
}

console.log("http://android-er.blogspot.com/");
console.log("http://helloraspberrypi.blogspot.com/");

console.log("node.js net server is waiting:");
for (var interface in networkInterfaces) {

    networkInterfaces[interface].forEach(function(details){
        
        if ((details.family=='IPv4') && !details.internal) {
            console.log(interface, details.address);  
        }
    });
}

console.log("port: ", port);

var netServer = net.createServer(callback_server_connection);
netServer.listen(port);


Next:
- Node.js server and client, run on Raspberry Pi


1 comment:

Unknown said...

I have a node js server, where i have two links(html) referencing an image and another link referencing a text file. I was these two links to be displayed in a list view on android device client side. How must i integrate the two?