New Post has been published on Toontuts | Toonlite Tutorial Blog | HTML5 Tutorials | Web Designing Tutorials
New Post has been published on http://www.toontuts.com/adding-websocket-support-to-phonegap-android-platform-make-the-default-socket-io-preferred-channel-selection/
Adding websocket support to Phonegap Android platform, make the default socket.IO preferred channel selection
HTML+CSS+Javascript can be used to build cross-platform mobile reference, really is very good, highly recommended.
Better yet, can be built using its cloud services (https://build.phonegap.com/apps ), after the native application written (guaranteed Home index.html, involving CSS/JS is stored in), packaged as a zip, upload, automatic deployment packages, automated build different platform for us, is very convenient.
On the surface, everything was perfect, but after a deployment to the Android system, found socket.IO websocket two-way channel cannot be used, socket.IO defaults to the XHR-long polling traffic patterns. Some frustration.
In the case of real-time interaction data are substantial, compared to XHR-long polling and JSONP polling,Websocket/Flashsocket features unsurpassed speed advantages with bi-directional data transfer channel, through observation can clearly feel it.
My Android system is 2.3, the native browser websocket Protocol is not supported (ucweb,QQ,opear mini supports a full HTML5 spec).
Phonegap APK package conversion, built-in browser called Android, thus resulting in websocket is not available.
According to research native Android 2/3.* browser does not support the websocket, Android 4.*, havenât tested.
How to identify browser support for HTML5, the browser visits http://html5test.com can access support for HTML5, and run.
Well, according to rumors, after the 2 version of Phonegap, adding websocket support for Android, but the current version is 1.7.
Animesh Kumar developed websocket-Android-phonegap project, have done that Phonegap support for websocket client protocol, using Java NIO preparation of websocket client protocol connections, and Phonegap supports a custom component, call each other open architecture supports JS and JAVA code, which led to webscoket.js in disguise.
Its DWR taste, but more flexible.
There is also a simple socket.IO Android client implementation:
https://github.com/koush/android-websockets#readme
Are interested in, you can refer to.
Was going to build a websocket client using the Netty, then combined with js, but there are open source implementations, not behind closed doors.
In the new Android Project in Eclipse project chatdemo
Animesh Kumar websocket-Android-phonegap Java files into the project phonegap-websocket-support.jar the package, stored in a Android projectâs libs directory
Websocket.js stored under the assets/www/js directory
Modify the project start class App.java
Add <script src= âjs/websocket.jsâ ></script>
A brief description of
1. App.java modifications:
import org.apache.cordova.DroidGap; import android.os.Bundle; import com.strumsoft.websocket.phonegap.WebSocketFactory; /** * * @author Toontuts * @time 2012-5-10 * @version 1.0 */ public class App extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/index.html"); / / Bind websocket support appView.addJavascriptInterface(new WebSocketFactory(appView), "WebSocketFactory"); } }
Ensure that inherits DroidGap, and specifying the binding statement:
//Bind the websocket support appView.addJavascriptInterface(new WebSocketFactory(appView), "WebSocketFactory");
JAVA-side setting is completed.
2. modification of client
Need to fiddle in the HTML page side, giving priority to set some environment variables loaded websocket.js, socket.IO detected websocket support.
Websocekt.js initialization code:
(function() { // window object var global = window; // WebSocket Object. All listener methods are cleaned up! var WebSocket = global.WebSocket = function(url) { // get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java) this.socket = WebSocketFactory.getInstance(url); // store in registry if(this.socket) { WebSocket.store[this.socket.getId()] = this; } else { throw new Error('Websocket instantiation failed! Address might be wrong.'); } }; // storage to hold websocket object for later invokation of event methods WebSocket.store = {}; // static event methods to call event methods on target websocket objects WebSocket.onmessage = function (evt) { WebSocket.store[evt._target]['onmessage'].call(global, evt); } WebSocket.onopen = function (evt) { WebSocket.store[evt._target]['onopen'].call(global, evt); } WebSocket.onclose = function (evt) { WebSocket.store[evt._target]['onclose'].call(global, evt); } WebSocket.onerror = function (evt) { WebSocket.store[evt._target]['onerror'].call(global, evt); } // instance event methods WebSocket.prototype.send = function(data) { this.socket.send(data); } WebSocket.prototype.close = function() { this.socket.close(); } WebSocket.prototype.getReadyState = function() { this.socket.getReadyState(); } ///////////// Must be overloaded WebSocket.prototype.onopen = function(){ throw new Error('onopen not implemented.'); }; // alerts message pushed from server WebSocket.prototype.onmessage = function(msg){ throw new Error('onmessage not implemented.'); }; / / Other prototype function, omit ...... })();
Need to pay attention to its initialization code:
/ / Window object
var global = window;
/ / WebSocket Object. All listener Methods are cleaned up!
var WebSocket = global.WebSocket = Function (url)
socket.io client websocket snippet:
(function (exports, io, global) { exports.websocket = WS; function WS (socket) { io.Transport.apply(this, arguments); }; io.util.inherit(WS, io.Transport); WS.prototype.name = 'websocket'; WS.prototype.open = function () { var query = io.util.query(this.socket.options.query) , self = this , Socket if (!Socket) { Socket = global.MozWebSocket || global.WebSocket; } this.websocket = new Socket(this.prepareUrl() + query); this.websocket.onopen = function () { self.onOpen(); self.socket.setBuffer(false); }; this.websocket.onmessage = function (ev) { self.onData(ev.data); }; this.websocket.onclose = function () { self.onClose(); self.socket.setBuffer(true); }; this.websocket.onerror = function (e) { self.onError(e); }; return this; }; WS.prototype.send = function (data) { this.websocket.send(data); return this; }; WS.prototype.payload = function (arr) { for (var i = 0, l = arr.length; i < l; i++) { this.packet(arr[i]); } return this; }; WS.prototype.close = function () { this.websocket.close(); return this; }; WS.prototype.onError = function (e) { this.socket.onError(e); }; WS.prototype.scheme = function () { return this.socket.options.secure ? 'wss' : 'ws'; }; WS.check = function () { return ('WebSocket' in global && !('__addTask' in WebSocket)) || 'MozWebSocket' in global; }; WS.xdomainCheck = function () { return true; }; io.transports.push('websocket'); })( 'undefined' != typeof io ? io.Transport : module.exports , 'undefined' != typeof io ? io : module.parent.exports , this );
Look at the websocket test function:
WS.check = function () {
return ('WebSocket' in global && !(' __addTask' in WebSocket))
|| 'MozWebSocket' in global;
};
Naturally, custom websocket.js and socket.IO is able to naturally link them together.
Must therefore be JS page load order is:
<!--Android platform you need to add other mobile platforms, such as IOS do not require--> <!--must be placed in front of the socket.IO.min.js--> <script src="js/websocket.js"></script> <script src="js/socket.io.min.js"></script>
At the end HTML page, we only need to add a line references, do the websocket socket.IO preference, the Android platform is very simple, is also used.
For other platforms, you do not need to be considered, simply packaged into ZIP package under the/chatdemo/assets/www directory (remember to get rid of), can be automatically uploaded to the cloud to build platform to build on.
Phonegap Android platform under support for websocket, steps are simple:
Build Android in the Eclipse project
Copy jar, and socekt.js to the directory
Modify App.java (other Android startup class method name is not the same, but the method body)
At Home or if you need to page socket.IO js medical front, add references