Over a million developers have joined DZone.

WebSockets in PhoneGap Projects

DZone's Guide to

WebSockets in PhoneGap Projects

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

I'm a big fan of the WebSockets API for all the real-time goodness it offers, but the iOS platform doesn't (currently) bake the WebSockets API in to mobile Safari. That sucks, particularly because I can enjoy making iOS native apps using awesome frameworks like PhoneGap. However, because I'm using PhoneGap, I can create a PhoneGap plugin that introduces WebSockets to my HTML & JavaScript. So that's what I did.


I'm assuming you've got your PhoneGap project and XCode to manage and build the project. These instructions are going to explain how to get WebSockets working in your project.

Step 1: Cocoa Async Socket

Download and include AsyncSocket.h/.m from the cocoaasyncsocket project in your project directory (or some subdirectory, as you please).

Next, drag these files (AsyncSocket.h/.m) in to the XCode project space - this will include the files properly when the project is built.

Step 2: PhoneGap Plugin: WebSocket

Now download (or fork) the PhoneGap-Plugin-WebSocket project. Now repeat the process you did with the Async project with the WebSocketCommand.h/.m files.

Next, copy websocket.js in to your www directory and include the following after you include phonegap.js:

<script src="websocket.js"></script>

Note: you can also release your project to the web and include the websocket.js script, because it will only introduce WebSockets if a) WebSockets aren't already available, and b) only if PhoneGap is in place.

So now you're read to rock and roll with native WebSocket support in your PhoneGap project.


Once you've followed the installation, usage is exactly the same as using a WebSocket normally:

var ws = new WebSocket('ws://example.com');
ws.onmessage = function () {
alert('a message was recieved');

ws.onopen = function () {
ws.send('I just connected!');

One small caveat, if you need the WebSocket straight away, you will need to wait until the deviceready event fires, but otherwise you can just create the socket on demand.

If you want to learn more about PhoneGap, my conference Full Frontal, is running a full day workshop with Brian LeRoux entirely on PhoneGap, so check it out!

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.


Published at DZone with permission of Remy Sharp, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}