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:
var server = require('http').createServer(); |
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:
|
To begin, we need to get the Socket.IO-client script. We can take it from the CDN like so:
<script type="text/javascript" src="cordova.js"></script> |
Now to add actual logic, let’s write things below the app.initialize
call. We might want to make sure that the device has loaded the application before running any of our code. We can do this like so:
<script type="text/javascript"> |
This event will fire when the application has fully loaded. To add some actual logic, we just need to fill in that function. Let’s make something that receives the data emitted by our server on socket connection, and bring a notification box to show that text. Here’s what you could do:
<script type="text/javascript"> |
Let’s run the emulator again with cordova emulate ios
, and here’s what you should see:
That’s it! I hope this will help to get you started! Have fun hacking!