Samstag, 21. Januar 2012

webOS: Open a socket

If you use Enyo or Mojo for your webOS application development, you cannot connect to a server that runs anything else than a http protocol. This limitation comes from webOS programs effectively running inside a web browser. Therefore they can make only http requests using XmlHttpRequest calls.

But webOS Version 2.X introduced support for node.js. Programs can use this library to open a socket to any server using any protocol. The downside is, that you have to do a little bit of work to get this thing moving: you have to write your own javascript service.

This code opens a connection to port 28820 on host 172.20.1.65 and sends the string "HELLO" with a line break. When it receives an response, it is written to the console.

// import node.js net library
var net = IMPORTS.require('net');

// constructor for service assistant
var socketAssistant = function() {
};

// function is called by framework to execute the service
socketAssistant.prototype.run = function(future) {
    // future contains the result of the function call
    // use it to transfer information to your program
    future.result = {
        reply : "Hello " + this.controller.args.name + "!"
    };

    // check if the node.js net library has been loaded
    if (!net) {
        console.error("net == NULL");
    }

    // create a new client connection
    var client = net.createConnection(28820, '172.20.1.65');

    // event handler when data arrives from the server
    client.on("data", function(data) {
        console.error("Received data: " + data.toString());
    });

    // event handler called after a connection has been established
    client.on("connect", function() {
        console.error("Connection established !");
        client.write("HELLO\n"));
    });

    // event handler called in case of an error
    client.on('end', function() {
        console.error("Connection killed.");
    }); 
};

The code is pretty simple but does not contain the framework needed to integrate it into a service. That is fodder for another post soon. Meanwhile take a look at the SDK documentation for writing javascript services.

Older versions of webOS only support node.js 0.2.3. Version 3.0.4 of webOS made an update to node.js 0.4.12 (see release notes). Be aware of that fact when using the node.js functions.

See the node.js (version 0.2.3) documentation for what you can do with the connection.

Keine Kommentare:

Kommentar veröffentlichen