找回密码
 立即注册

QQ登录

只需一步,快速开始

hbuilder离线打包 websocket全局共享


离线打包后手写websocket

用到的jar包  android-support-v4.jar



  1. package com.websocket;

  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import com.koushikdutta.async.callback.CompletedCallback;
  5. import com.koushikdutta.async.http.AsyncHttpClient;
  6. import com.koushikdutta.async.http.WebSocket;
  7. import android.R.plurals;
  8. import android.content.Context;
  9. import android.util.Log;
  10. import android.webkit.WebView;
  11. import com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback;
  12. import io.dcloud.WebAppActivity;
  13. import io.dcloud.common.DHInterface.IApp;
  14. import io.dcloud.common.DHInterface.IWebview;
  15. import io.dcloud.common.DHInterface.StandardFeature;
  16. import io.dcloud.common.util.JSUtil;
  17. import io.dcloud.feature.internal.sdk.SDK;


  18. public class HWebSocket extends StandardFeature{
  19. private static int tryTime = 1;
  20. private static WebSocket webSocket = null;
  21. public static void webConnect(final String url) {

  22.         if (webSocket == null) {
  23.             try {
  24.             
  25.                 AsyncHttpClient.getDefaultInstance().websocket(url, null, new WebSocketConnectCallback() {
  26.                     @Override
  27.                     public void onCompleted(Exception ex, WebSocket _webSocket) {
  28.                     if(ex!=null) {
  29.                     
  30.                     //获取webview
  31.                             ArrayList<IWebview> ss = SDK.obtainAllIWebview();
  32.                             for (IWebview iWebview : ss) {
  33.                                     iWebview.evalJS("onClosed('0')");
  34.                             }
  35.                             ex.printStackTrace();
  36.                     }
  37.                         webSocket = _webSocket;
  38.                         webSocket.setStringCallback(new WebSocket.StringCallback() {
  39.                             @Override
  40.                             public void onStringAvailable(String s) {
  41.                                 Log.d("websocket",s);
  42.                                 //获取webview
  43.                                 ArrayList<IWebview> ss = SDK.obtainAllIWebview();
  44.                                 for (IWebview iWebview : ss) {
  45. //                                    if (iWebview.getOriginalUrl().equals("messageList.html")) {
  46. //                                 if((s.indexOf("Question")!=-1 || s.indexOf("GroupQuestion")!=-1 || s.indexOf("SingleQuestion")!=-1 || s.indexOf("DrawingBoardQuestion")!=-1) && (iWebview.getOriginalUrl()=="ClassroomInteraction/st_answer.html" || iWebview.getOriginalUrl()=="learnTast/drawingBoard.html")){
  47. //                                 continue;
  48. //                                 }
  49.                                 
  50.                                 WebView vs = iWebview.obtainWebview();
  51.                                 String url  = iWebview.getOriginalUrl();
  52.                                         iWebview.evalJS("wsRecive('" + s + "')");
  53. //                                        break;
  54. //                                    }
  55.                                 }
  56.                             }
  57.                         });
  58.                         webSocket.setClosedCallback(new CompletedCallback() {
  59.                             @Override
  60.                             public void onCompleted(Exception ex) {
  61.                                 try {
  62.                                     if (ex != null)
  63.                                         Log.e("WebSocket", "Error");
  64.                                 } finally {
  65.                                 ArrayList<IWebview> ss = SDK.obtainAllIWebview();
  66.                                 
  67.                                 for (IWebview iWebview : ss) {
  68. //                                      if (iWebview.getOriginalUrl().equals("messageList.html")) {
  69.                                          iWebview.evalJS("onClosed('0')");
  70. //                                      }
  71.                         };
  72.                                 }
  73.                             }
  74.                         });
  75.                     }
  76.                 });
  77.             }catch(Exception e){
  78.             //socket关闭时候事件触发
  79.             ArrayList<IWebview> ss = SDK.obtainAllIWebview();
  80.             for (IWebview iWebview : ss) {
  81. //                 if (iWebview.getOriginalUrl().equals("messageList.html")) {
  82.             iWebview.evalJS("onClosed('0')");
  83.             };
  84.             e.printStackTrace();
  85.             }
  86.             finally {
  87. //                if (tryTime <= 1) {
  88. //                    tryTime += 1;
  89. //                    webConnect(url);
  90. //                }
  91. //             ArrayList<IWebview> ss = SDK.obtainAllIWebview();
  92. //             for (IWebview iWebview : ss) {
  93. ////                 if (iWebview.getOriginalUrl().equals("messageList.html")) {
  94. //             iWebview.evalJS("onClosed('0')");
  95. //             break;
  96. //             };
  97.             }
  98.         }
  99.     }

  100. //发送socket
  101. public static void sendMsg(String msg) {
  102. // show(msg);
  103.         if (webSocket != null && webSocket.isOpen()) {
  104.         Log.d("c", msg);
  105.             webSocket.send(msg);
  106.             Log.d("s",webSocket.isOpen()+"");
  107.         }
  108.     }


  109. //关闭socket
  110. public static void close() {
  111.         if (webSocket != null && webSocket.isOpen()) {
  112.             webSocket.close();
  113.             webSocket = null;
  114.         }
  115.     }

  116. //检查ip是否畅通
  117. public static String  pingIpAddress(String ipAddress) {
  118. String falg = "false";
  119. Process process = null;  
  120.        try {
  121.          process = Runtime.getRuntime().exec("ping -c 1 -i 0.5 -W 1 " + ipAddress);  
  122.            int status = process.waitFor();
  123.            if (status == 0) {
  124.                falg = "true";
  125.            } else {  
  126.                falg = "false";
  127.            }
  128.        } catch (IOException e) {
  129.            e.printStackTrace();
  130.        } catch (InterruptedException e) {
  131.            e.printStackTrace();
  132.        }
  133.        return JSUtil.wrapJsVar(falg);
  134.    }

  135. }


复制代码



js端 代码



  1. var WsUrl = "ws://192.168.2.167:8080";
  2. var ip = "192.168.2.167";
  3. var port = "8080";
  4. if(localStorage.getItem("ip") != null && localStorage.getItem("ip") != "") {
  5.     ip = localStorage.getItem("ip");
  6.     WsUrl = "ws://"+ip+":"+port;
  7. }




  8. //var ajaxUrl = "";
  9. // 内网ip是否畅通 畅通则打开websocket
  10. function pingIpAddress() {
  11.     if(localStorage.getItem("ip") != null && localStorage.getItem("ip") != "") {
  12.         ip = localStorage.getItem("ip");
  13.         WsUrl = "ws://"+ip+":"+port;
  14.     }
  15.     if(mui.os.android) {
  16.         
  17.         try{
  18.             var Toolkit = plus.android.importClass("com.websocket.HWebSocket");
  19.             if(Toolkit) {
  20.             var t = eval(Toolkit.pingIpAddress(ip));
  21.             if(t == 'true') {
  22.                 return true;
  23.             } else {
  24.                 return false;
  25.             }
  26.             } else {
  27.                 plus.nativeUI.alert("IM服务器连接失败");
  28.                 return false;
  29.             }
  30.         }catch(e){
  31. //           plus.nativeUI.alert("IM服务器连接失败");
  32.                 return false;
  33.         }
  34.         
  35.     }
  36. }


  37. //初始化socket
  38. function createWs() {


  39.     if(mui.os.ios) {
  40.         if('WebSocket' in window) {
  41.             debug("WebSocket")
  42.             wsClient = new WebSocket(WsUrl);
  43.         } else if('MozWebSocket' in window) {
  44.             debug("MozWebSocket")
  45.             wsClient = new MozWebSocket(WsUrl);
  46.         }
  47.         wsClient.onopen = function() {
  48.             onOpen()
  49.         };
  50.         wsClient.onclose = function() {
  51.             onClose()
  52.         };
  53.         wsClient.onmessage = function(evt) {
  54.             onMessage(evt)
  55.         };
  56.         wsClient.onerror = function() {
  57.             onError()
  58.         };
  59.     } else if(mui.os.android) {
  60.         var Toolkit = null;
  61.         try{
  62.             Toolkit = plus.android.importClass("com.websocket.HWebSocket");
  63.             if(Toolkit) {
  64.                 //var wifiInfo = new Toolkit();
  65.                 Toolkit.webConnect(WsUrl);
  66.                 //如果可以连接则为网络为内网
  67.                 localStorage.setItem("net_flag", "true");
  68.             } else {
  69.                 plus.nativeUI.alert("IM服务器连接失败");
  70.             }
  71.         }catch(e){
  72.             localStorage.setItem("net_flag", "false");
  73.             return false;
  74.         }
  75.     }
  76. }


  77. //发送socket
  78. function sendMsg(msg) {


  79.     if(mui.os.ios) {
  80.         //缓存本地
  81.         if(wsClient.readyState == WebSocket.OPEN) {
  82.             wsClient.send(JSON.stringify(msg));
  83.             _msg = null;
  84.         } else {
  85.             _msg = msg;
  86.             createWs();
  87.         }
  88.     } else if(mui.os.android) {
  89.         var Toolkit = null;
  90.         try{
  91.             Toolkit = plus.android.importClass("com.websocket.HWebSocket");
  92.             if(Toolkit) {
  93.                 Toolkit.sendMsg(msg);
  94.             } else {
  95.                 plus.nativeUI.alert("IM服务器连接失败");
  96.             }
  97.         }catch(e){
  98.             return false;
  99.         }
  100.     }
  101. }



  102. //socket 返回值
  103. function wsRecive(e) {

  104. }

  105. //   0 错误断开 1 自然断开
  106. function onClosed(e) {
  107.     if(e == '0') {
  108.         var ws = plus.webview.currentWebview();


  109.         if(ws.id=='entrance'){
  110.             return;
  111.         }
  112.         var ars = plus.webview.getDisplayWebview();
  113.         if(ars[ars.length-1].id==ws.id){
  114.             mui.alert("连接已断开,请重启程序");
  115.         }
  116.         
  117.     }
  118. }


  119. //关闭socket方法
  120. var close =  function() {
  121.     var Toolkit = null;
  122.     try{   
  123.         Toolkit = plus.android.importClass("com.websocket.HWebSocket");
  124.         if(Toolkit) {
  125.             Toolkit.close();
  126.         } else {
  127.             plus.nativeUI.alert("IM服务器连接失败");
  128.         }
  129.     }catch(e){
  130.         return false;
  131.     }
  132. }
复制代码




配置hbuilder 类引用

/assets/data/dcloud_properties.xml  

<feature name="HWebSocket" value="com.websocket.HWebSocket"></feature>

本教程由无限星辰工作室CRX349独家整理和提供,转载请注明地址,谢谢。本文地址:https://www.xmspace.net/thread-616-1-1.html
无限星辰工作室  好集导航 Discuz全集下载  星辰站长网  集热爱361  一品文学  手机小游戏合集   海外空间网 星辰api  星辰支付二维码管理平台 阿里云服务器 腾讯云服务器
服务Discuz!建站|DiscuzQ配置|二开|小程序|APP|搬家|挂马清理|防护|Win/Linux环境搭建|优化|运维|
服务理念:专业 诚信 友好QQ842062626 服务项目 Q群315524225

发表于 2018-6-6 23:32:46 | 显示全部楼层 |阅读模式

回复 | 使用道具 举报

该帖共收到 0 条回复!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

美图秀

    • fastadmin 后台界面使用字段数组类型
    • Discuz!x3.5 修改标题高亮颜色
    • Discuz!x3.5 应用中心 下载应用一直下载中
    • 帖子定时显示
    • 论坛辅助审核
拖动客服框
Online Service
点击这里给我发消息
点击这里联系我们
微信扫一扫
在线客服
快速回复 返回顶部 返回列表