Socket.IO — Apache Cordova ===================================== Since Apache Cordova apps are written mostly in JS, it is actually really easy to use Socket.IO! Let’s walk through a small example. First we prepare a simple server: .. code:: js var server = require('http').createServer(); var io = require('socket.io')(server); io.sockets.on('connection', function (socket) { console.log('socket connected'); socket.on('disconnect', function () { console.log('socket disconnected'); }); socket.emit('text', 'wow. such event. very real time.'); }); server.listen(3000); This server will simply listen to Socket.IO client connections, and will emit some text to them via a ``text`` event. Now let’s get get down to the point. We want to start off by creating a new Cordova project to start modifying. Let’s start from scratch. Running :: npm install -g cordova will install the actual Cordova cli tool we use to create projects, install/remove dependencies, and launch our emulator among other things. :: cordova create socket.io-example socket.io.example socket.io-example will make a new project template for us to start modifying. Feel free to poke around the newly created folder, called ``socket.io-example`` and take a look at some of the created files. You should now be in the project folder. If you didn’t navigate there yet in command line, do it now with ``cd socket.io-example``. Since I’m developing this example on OS X, I’m going to build for iOS. You could do it similarly for Android. To add the build target, run the following: :: cordova platform add ios Next we want to build all the native components. We can do this by running :: cordova build ios Now let’s actually run the template application to see that everything is working. If you are on OS X, you can install the iOS emulator like so :: brew install ios-sim You should see the emulator open up with something like this when running ``cordova emulate ios``: Now that you see everything working with the actual setup, let’s start write some code. Open up ``www/index.html`` in your project directory. It should look something like this: .. code:: html
Connecting to Device
Device is Ready