Let's talk about websocket first. As the name suggests, websocket is also a socket used for communication. It is only used on the web, so it is called websocket. Websocket is one of the html5 specifications and is supported by mainstream browsers such as chrome and ff. However, in our native android browser ...... Webview in android is also the core of the native browser, so it is equally tragic.
After the emergence of websocket, Someone developed socket. io. What is this? In fact, it does one thing, that is, encapsulating websocket, so that even platforms that do not support websocket can communicate normally when calling socket. io. In addition, when using socket. io, no matter the support does not support websocket, only one piece of code is required.
With socket. io, we can use socket communication in the webview of the android environment. However, android does not support websocket. How does socket. io implement socket communication? In the past, socket. io was implemented in other ways without websocket supported by the platform, such as xhr and flashsocket. In android, socket. io is implemented in xhr mode.
Xhr implements communication, but compared with websocket, xhr achieves incomparable performance. Is there a way for android to implement real websocket? Yes, someone has come up with a roundabout solution:
Using the feature that webview and page can be called together, java nio is used to implement websocket again. This is a genuine socket!
In fact, someone has implemented this method, and you only need to import some plug-ins and a few modifications to the code, you can use the socket. io code to implement websocket in android webview.
Github address: https://github.com/koush/android-websockets#readme
The following is a brief introduction to the usage:
Create an Android Project in Eclipse
Pack animesh kumar's websocket-android-phonegap project java file WebSocketFactory. java and WebSocket. java into a jar package, store it in the libs directory of the android project, and import it to the project.
Store websocket. js in the assets/www/js directory
Modify project startup class App. java
Add the following code to the onCreate method of App. java:
appView.addJavascriptInterface(new WebSocketFactory(appView), "WebSocketFactory");
Add <script src = \ '# \' "/websocket. js"> </script>
Note that this line must be loaded before loading socket. io. js.
This article from the "snow floating July" blog, please be sure to keep this source http://xuepiaoqiyue.blog.51cto.com/4391594/1285791