Chinaunix首页 | 论坛 | 博客
  • 博客访问: 190769
  • 博文数量: 111
  • 博客积分: 3010
  • 博客等级: 中校
  • 技术积分: 1240
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-07 07:46
文章分类

全部博文(111)

文章存档

2015年(2)

2014年(1)

2011年(1)

2010年(7)

2009年(100)

我的朋友

分类: HTML5

2015-03-08 17:52:15

有朋友问能不能在和开发的APP里发送UDP数据,HTML5里只能用HTTPS/HTTP/WebSocket几种通讯方式,要使用UDP需要通过phonegap打包成APK等特定平台的安装包。为此我写了一个UDP的例子,但是运行时遇到的问题,所以花了些时间去研究phonegap加载udp插件的过程。

1.添加需要的插件

在cordova_plugins.js中存放了APP引用的插件列表,可以用phonegap plugin add添加,如:

phonegap plugin add org.chromium.sockets.tcp

2.加载cordova_plugins.js

点击(此处)折叠或打开

  1. exports.load = function(callback) {
  2.     var pathPrefix = findCordovaPath();
  3.     if (pathPrefix === null) {
  4.         console.log('Could not find cordova.js script tag. Plugin loading may fail.');
  5.         pathPrefix = '';
  6.     }
  7.     injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function() {
  8.         var moduleList = require("cordova/plugin_list");
  9.         handlePluginsObject(pathPrefix, moduleList, callback);
  10.     }, callback);
  11. };


  12. function handlePluginsObject(path, moduleList, finishPluginLoading) {
  13.     // Now inject the scripts.
  14.     var scriptCounter = moduleList.length;


  15.     if (!scriptCounter) {
  16.         finishPluginLoading();
  17.         return;
  18.     }
  19.     function scriptLoadedCallback() {
  20.         if (!--scriptCounter) {
  21.             onScriptLoadingComplete(moduleList, finishPluginLoading);
  22.         }
  23.     }


  24.     for (var i = 0; i < moduleList.length; i++) {
  25.         injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);
  26.     }
  27. }


3.插件的JS文件中调用cordova.define把自己注册到phonegap的模块列表里

点击(此处)折叠或打开

  1. cordova.define("in.girish.datagram.datagram", function(require, exports, module) {

4.调用者不需要直接引用插件的JS,而是调用cordova.require去从插件列表中查找,然后使用

点击(此处)折叠或打开

  1. var dgram = cordova.require('in.girish.datagram.datagram'); var client = dgram.createSocket("udp4");
  2.         client.send("hello cantk", "192.168.1.168", 41234, function(err) { console.log(err ? JSON.stringify(err) : "success");
  3.           client.close();
  4.         })


插件使用者只需要关注第1步和第4步即可。第2步由phonegap实现,第3步由插件提供者实现。

但是第3步要注意,老版本要求插件自己调用cordova.define,新版本会自动加上这个定义。所以新版本phonegap使用老版本的插件就会存在问题,导致重复定义而无法使用,需要手动删除这个定义。

阅读(417) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~