关于 socket 通信

**WebServer**
package com.tools.payhelper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.tools.payhelper.utils.AbSharedUtil;
import com.tools.payhelper.utils.BitmapUtil;
import com.tools.payhelper.utils.DBManager;
import com.tools.payhelper.utils.OrderBean;
import com.tools.payhelper.utils.PayHelperUtils;
import com.tools.payhelper.utils.QrCodeBean;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response;
import fi.iki.elonen.NanoHTTPD.Response.Status;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;

public class WebServer extends NanoHTTPD {
    public static String MSGRECEIVED_ACTION = "com.tools.payhelper.msgreceived";
    private static final String REQUEST_GETPAY = "/getpay";
    private static final String REQUEST_GETRESULT = "/getresult";
    private static final String REQUEST_QUERY = "/query";
    private static final String REQUEST_ROOT = "/";
    private static final String REQUEST_WECHAT = "/wechat";
    public static final String TAG = WebServer.class.getSimpleName();
    private Context context;

    public WebServer(Context context, int serverport) {
        super(serverport);
        this.context = context;
    }

    public Response serve(IHTTPSession session) {
        WebServer webServer = this;
        IHTTPSession iHTTPSession = session;
        String str = TAG;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("OnRequest: ");
        stringBuilder.append(session.getUri());
        Log.d(str, stringBuilder.toString());
        try {
            if (REQUEST_ROOT.equals(session.getUri())) {
                return responseRootPage(session);
            }
            String str2 = "支付宝最大支持单笔50000元支付!";
            String str3 = "wechat";
            String account = "";
            String str4 = "type";
            String str5 = "mark";
            String str6 = "com.tencent.mobileqq";
            String str7 = "com.tencent.mm";
            String str8 = "com.eg.android.AlipayGphone";
            String str9 = "qqpay";
            String str10 = "money";
            String str11 = "wxpay";
            String str12 = "alipay";
            String money;
            List<QrCodeBean> qrCodeBeans;
            DBManager dbManager;
            Object qrCodeBeans2;
            if (REQUEST_WECHAT.equals(session.getUri())) {
                Map<String, String> params = session.getParms();
                money = (String) params.get(str10);
                str5 = (String) params.get(str5);
                str4 = (String) params.get(str4);
                if (str4 == null || str4.equals(account) != null) {
                    str4 = str3;
                }
                double m = Double.parseDouble(money);
                if (str4.equals(str12)) {
                    if (m > 50000.0d) {
                        return responseText(iHTTPSession, str2);
                    }
                } else if (str4.equals(str11)) {
                    if (m > 15000.0d) {
                        return responseText(iHTTPSession, "微信最大支持单笔15000元支付!");
                    }
                } else if (str4.equals(str9)) {
                    if (m > 30000.0d) {
                        return responseText(iHTTPSession, "QQ最大支持单笔30000元支付!");
                    }
                    if (str5.length() > 12) {
                        return responseText(iHTTPSession, "QQ备注长度不能超过12位!");
                    }
                }
                if (str4.equals(str12) && !PayHelperUtils.isAppRunning(webServer.context, str8)) {
                    PayHelperUtils.startAPP(webServer.context, str8);
                } else if (str4.equals(str11) && !PayHelperUtils.isAppRunning(webServer.context, str7)) {
                    PayHelperUtils.startAPP(webServer.context, str7);
                } else if (str4.equals(str9) && !PayHelperUtils.isAppRunning(webServer.context, str6)) {
                    PayHelperUtils.startAPP(webServer.context, str6);
                }
                qrCodeBeans2 = new ArrayList();
                dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                PayHelperUtils.sendAppMsg(money, str5, str4, webServer.context);
                int times = 0;
                while (times < 30 && qrCodeBeans2.size() == 0) {
                    qrCodeBeans2 = dbManager.FindQrCodes(money, str5, str4);
                    times++;
                    Thread.sleep(500);
                }
                if (qrCodeBeans2.size() == 0) {
                    PayHelperUtils.startAPP();
                    return responseText(iHTTPSession, "获取超时....");
                }
                str7 = ((QrCodeBean) qrCodeBeans2.get(0)).getPayurl();
                PayHelperUtils.startAPP();
                return responseQRCode(iHTTPSession, str7, str5);
            }
            money = "msg";
            if (REQUEST_GETPAY.equals(session.getUri())) {
                JSONObject jsonObject = new JSONObject();
                String str13 = str6;
                Map<String, String> params2 = session.getParms();
                String money2 = (String) params2.get(str10);
                String mark = (String) params2.get(str5);
                Map<String, String> map = params2;
                str6 = (String) params2.get(str4);
                if (str6 == null || str6.equals(account)) {
                    str6 = str11;
                }
                double m2 = Double.parseDouble(money2);
                if (str6.equals(str12)) {
                    account = AbSharedUtil.getString(webServer.context, str12);
                    if (m2 > 50000.0d) {
                        jsonObject.put(money, str2);
                        return responseJson(iHTTPSession, jsonObject.toString());
                    }
                } else if (str6.equals(str11)) {
                    account = AbSharedUtil.getString(webServer.context, str3);
                    if (m2 > 15000.0d) {
                        jsonObject.put(money, "微信最大支持单笔15000元支付!");
                        return responseJson(iHTTPSession, jsonObject.toString());
                    }
                } else if (str6.equals(str9)) {
                    account = AbSharedUtil.getString(webServer.context, "qq");
                    if (m2 > 30000.0d) {
                        return responseText(iHTTPSession, "QQ最大支持单笔30000元支付!");
                    }
                    if (mark.length() > 12) {
                        return responseText(iHTTPSession, "QQ备注长度不能超过12位!");
                    }
                }
                if (str6.equals(str12) && !PayHelperUtils.isAppRunning(webServer.context, str8)) {
                    PayHelperUtils.startAPP(webServer.context, str8);
                } else if (str6.equals(str11) && !PayHelperUtils.isAppRunning(webServer.context, str7)) {
                    PayHelperUtils.startAPP(webServer.context, str7);
                } else if (str6.equals(str9)) {
                    str12 = str13;
                    if (!PayHelperUtils.isAppRunning(webServer.context, str12)) {
                        PayHelperUtils.startAPP(webServer.context, str12);
                    }
                }
                qrCodeBeans2 = new ArrayList();
                dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                str7 = money2;
                str8 = mark;
                PayHelperUtils.sendAppMsg(str7, str8, str6, webServer.context);
                int times2 = 0;
                while (times2 < 30 && qrCodeBeans2.size() == 0) {
                    qrCodeBeans2 = dbManager.FindQrCodes(str7, str8, str6);
                    times2++;
                    Thread.sleep(500);
                }
                if (qrCodeBeans2.size() == 0) {
                    PayHelperUtils.startAPP();
                    jsonObject.put(money, "获取超时");
                    return responseJson(iHTTPSession, jsonObject.toString());
                }
                str9 = ((QrCodeBean) qrCodeBeans2.get(0)).getPayurl();
                PayHelperUtils.startAPP();
                jsonObject.put(money, "获取成功");
                jsonObject.put("payurl", str9);
                jsonObject.put(str5, str8);
                jsonObject.put(str10, str7);
                jsonObject.put(str4, str6);
                if (!TextUtils.isEmpty(account)) {
                    jsonObject.put("account", account);
                }
                return responseJson(iHTTPSession, jsonObject.toString());
            } else if (REQUEST_QUERY.equals(session.getUri())) {
                str2 = (String) session.getParms().get("no");
                List<OrderBean> orderBeans = new ArrayList();
                orderBeans = new DBManager(CustomApplcation.getInstance().getApplicationContext()).FindOrders(str2);
                if (orderBeans == null || orderBeans.size() <= 0) {
                    return responseText(iHTTPSession, "当前订单未支付....");
                }
                account = PayHelperUtils.stampToDate(((OrderBean) orderBeans.get(0)).getDt());
                StringBuilder stringBuilder2 = new StringBuilder();
                stringBuilder2.append("当前订单已支付,支付时间:");
                stringBuilder2.append(account);
                stringBuilder2.append("....");
                return responseText(iHTTPSession, stringBuilder2.toString());
            } else if (!REQUEST_GETRESULT.equals(session.getUri())) {
                return response404(iHTTPSession, session.getUri());
            } else {
                str2 = (String) session.getParms().get("trade_no");
                orderBeans = new ArrayList();
                orderBeans = new DBManager(CustomApplcation.getInstance().getApplicationContext()).FindOrders(str2);
                JSONObject jsonObject2 = new JSONObject();
                str4 = AbSharedUtil.getString(webServer.context, "returnurl");
                if (orderBeans == null || orderBeans.size() <= 0) {
                    jsonObject2.put(money, "未支付");
                    return responseJson(iHTTPSession, jsonObject2.toString());
                }
                str6 = ((OrderBean) orderBeans.get(0)).getDt();
                str5 = ((OrderBean) orderBeans.get(0)).getMoney();
                str7 = PayHelperUtils.stampToDate(str6);
                jsonObject2.put(money, "支付成功");
                jsonObject2.put("paytime", str7);
                jsonObject2.put(str10, str5);
                if (!TextUtils.isEmpty(str4)) {
                    jsonObject2.put("returnurl", str4);
                }
                return responseJson(iHTTPSession, jsonObject2.toString());
            }
        } catch (Exception e) {
            return response404(iHTTPSession, e.getMessage());
        }
    }

    public Response responseRootPage(IHTTPSession session) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("Hello World!");
        builder.append("</body></html>\n");
        return NanoHTTPD.newFixedLengthResponse(builder.toString());
    }

    public Response responseQRCode(IHTTPSession session, String QRText, String no) {
        String imgbase64 = BitmapUtil.bitmapToBase64(BitmapUtil.createQRImage(QRText, 240, null));
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\"data:image/gif;base64,");
        stringBuilder.append(imgbase64);
        stringBuilder.append("\"");
        imgbase64 = stringBuilder.toString();
        stringBuilder = new StringBuilder();
        stringBuilder.append("<!DOCTYPE html><html><body>");
        stringBuilder.append("<div style=\"width:100%;height:100%;text-align:center;padding-top:20px;\">");
        stringBuilder.append("二维码生成测试<br>");
        stringBuilder.append("<image ");
        StringBuilder stringBuilder2 = new StringBuilder();
        stringBuilder2.append("src=");
        stringBuilder2.append(imgbase64);
        stringBuilder2.append(" >");
        stringBuilder.append(stringBuilder2.toString());
        stringBuilder.append("</image><br>");
        String url = new StringBuilder();
        url.append("http://");
        url.append((String) session.getHeaders().get("host"));
        url = url.toString();
        StringBuilder stringBuilder3 = new StringBuilder();
        stringBuilder3.append("获取成功,查询订单是否支付:<a href='");
        stringBuilder3.append(url);
        stringBuilder3.append("/query?no=");
        stringBuilder3.append(no);
        stringBuilder3.append("' target='_blank'>查询</a><br><br>");
        stringBuilder.append(stringBuilder3.toString());
        stringBuilder.append("</div>");
        stringBuilder.append("</body></html>\n");
        Log.i("server", stringBuilder.toString());
        return NanoHTTPD.newFixedLengthResponse(Status.OK, "text/html;charset=UTF-8", stringBuilder.toString());
    }

    public Response responseText(IHTTPSession session, String text) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("<div style=\"width:100%;height:100%;text-align:center;padding-top:20px;\">");
        builder.append(text);
        builder.append("</div>");
        builder.append("</body></html>\n");
        Log.i("server", builder.toString());
        return NanoHTTPD.newFixedLengthResponse(Status.OK, "text/html;charset=UTF-8", builder.toString());
    }

    public Response responseJson(IHTTPSession session, String json) {
        Log.i("server", json);
        return NanoHTTPD.newFixedLengthResponse(Status.OK, "application/json;charset=UTF-8", json);
    }

    public Response response404(IHTTPSession session, String url) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Sorry, Can't Found ");
        stringBuilder.append(url);
        stringBuilder.append(" !");
        builder.append(stringBuilder.toString());
        builder.append("</body></html>\n");
        return NanoHTTPD.newFixedLengthResponse(builder.toString());
    }

    protected String getQuotaStr(String text) {
        StringBuilder stringBuilder = new StringBuilder();
        String str = "\"";
        stringBuilder.append(str);
        stringBuilder.append(text);
        stringBuilder.append(str);
        return stringBuilder.toString();
    }
}

uuSocketIO

package com.tools.payhelper.socket;

import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import com.google.myjson.Gson;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import com.neovisionaries.ws.client.WebSocketListener;
import com.neovisionaries.ws.client.WebSocketState;
import com.tools.payhelper.BuildConfig;
import com.tools.payhelper.CustomApplcation;
import com.tools.payhelper.MainActivity;
import com.tools.payhelper.SocketStatusListener;
import com.tools.payhelper.app.Constans;
import com.tools.payhelper.socket.Request.Builder;
import com.tools.payhelper.socket.bean.BaseAction;
import com.tools.payhelper.socket.bean.BindAction;
import com.tools.payhelper.socket.bean.QrcodeResponse;
import com.tools.payhelper.socket.bean.TaskResonse;
import com.tools.payhelper.socket.bean.TimeOutWrapper;
import com.tools.payhelper.socket.bean.TipsAction;
import com.tools.payhelper.utils.AbSharedUtil;
import com.tools.payhelper.utils.PayHelperUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.helpers.FileWatchdog;

public class UUSocketIO {
    private static final int CONNECT_TIMEOUT = 5000;
    public static final String DEF_CONN_KEY = "123456";
    private static final String DEF_RELEASE_URL = "ws://134.175.147.217:7373";
    private static final String DEF_TEST_URL = "ws://134.175.147.217:7373";
    private static final String DEF_URL = "ws://134.175.147.217:7373";
    private static final int FRAME_QUEUE_SIZE = 5;
    private static final long HEARTBEAT_INTERVAL = 10000;
    private static final int REQUEST_TIMEOUT = 3000;
    private final int ERROR_HANDLE;
    private final int SUCCESS_HANDLE;
    private final String TAG;
    private int authTimes;
    private ScheduledExecutorService executor;
    private int heartbeatFailCount;
    private Runnable heartbeatTask;
    private Context mContext;
    private Handler mHandler;
    private WsListener mListener;
    private Runnable mReconnectTask;
    SocketStatusListener mSocketStatusListener;
    private WsStatus mStatus;
    private long maxInterval;
    private long minInterval;
    public boolean needReConn;
    private int reconnectCount;
    private long sendTime;
    private AtomicLong seqId;
    public Map<String, TimeOutWrapper> taskes;
    private String url;
    private WebSocket ws;

    /* renamed from: com.tools.payhelper.socket.UUSocketIO$2 */
    class C03902 implements Runnable {
        C03902() {
        }

        public void run() {
            if (System.currentTimeMillis() - UUSocketIO.this.sendTime >= UUSocketIO.HEARTBEAT_INTERVAL) {
                UUSocketIO.this.ws.sendPing();
                UUSocketIO.this.heartbeatFailCount = UUSocketIO.this.heartbeatFailCount + 1;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("sendPing...heartbeatFailCount = ");
                stringBuilder.append(UUSocketIO.this.heartbeatFailCount);
                String str = "UUSocketIO";
                Log.i(str, stringBuilder.toString());
                if (UUSocketIO.this.heartbeatFailCount >= 3) {
                    UUSocketIO.this.reconnect();
                    stringBuilder = new StringBuilder();
                    stringBuilder.append("reconnect...heartbeatFailCount = ");
                    stringBuilder.append(UUSocketIO.this.heartbeatFailCount);
                    Log.i(str, stringBuilder.toString());
                    UUSocketIO.this.heartbeatFailCount = 0;
                }
            }
            UUSocketIO.this.sendTime = System.currentTimeMillis();
            UUSocketIO.this.mHandler.postDelayed(this, UUSocketIO.HEARTBEAT_INTERVAL);
        }
    }

    /* renamed from: com.tools.payhelper.socket.UUSocketIO$3 */
    class C03913 implements Runnable {
        C03913() {
        }

        public void run() {
            try {
                UUSocketIO.this.ws = new WebSocketFactory().createSocket(UUSocketIO.this.url, 5000).setFrameQueueSize(5).setMissingCloseFrameAllowed(false).addListener(UUSocketIO.this.mListener = new WsListener()).connectAsynchronously();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static class WsManagerHolder {
        private static UUSocketIO mInstance = new UUSocketIO();

        private WsManagerHolder() {
        }
    }

    class WsListener extends WebSocketAdapter {
        WsListener() {
        }

        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            super.onTextMessage(websocket, text);
            UUSocketIO.this.msgFromSever(text);
        }

        public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
            super.onConnected(websocket, headers);
            String str = "连接成功";
            Log.i("UUSocketIO", str);
            UUSocketIO.this.authTimes = 0;
            MainActivity.sendmsg(str);
            if (UUSocketIO.this.mSocketStatusListener != null) {
                UUSocketIO.this.mSocketStatusListener.start();
            }
            UUSocketIO.this.setStatus(WsStatus.CONNECT_SUCCESS);
            UUSocketIO.this.cancelReconnect();
            UUSocketIO.this.doAuth();
            UUSocketIO.this.startHeartbeat();
        }

        public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
            super.onConnectError(websocket, exception);
            if (UUSocketIO.this.mSocketStatusListener != null) {
                UUSocketIO.this.mSocketStatusListener.stop();
            }
            UUSocketIO.this.authTimes = 0;
            String str = "连接错误";
            Log.i("UUSocketIO", str);
            MainActivity.sendmsg(str);
            UUSocketIO.this.setStatus(WsStatus.CONNECT_FAIL);
            UUSocketIO.this.reconnect();
        }

        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            String str = "断开连接";
            Log.i("UUSocketIO", str);
            UUSocketIO.this.authTimes = 0;
            MainActivity.sendmsg(str);
            if (UUSocketIO.this.mSocketStatusListener != null) {
                UUSocketIO.this.mSocketStatusListener.stop();
            }
            UUSocketIO.this.setStatus(WsStatus.CONNECT_FAIL);
            if (UUSocketIO.this.needReConn) {
                UUSocketIO.this.reconnect();
            }
        }

        public void onPingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
            super.onPingFrame(websocket, frame);
            Log.i("UUSocketIO", "onPingFrame...");
        }

        public void onPongFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
            super.onPongFrame(websocket, frame);
            Log.i("UUSocketIO", "onPongFrame****");
            UUSocketIO.this.heartbeatFailCount = UUSocketIO.this.heartbeatFailCount - 1;
        }
    }

    /* synthetic */ UUSocketIO(C03891 x0) {
        this();
    }

    static {
        boolean z = BuildConfig.DEBUG;
    }

    public SocketStatusListener getmSocketStatusListener() {
        return this.mSocketStatusListener;
    }

    public void setmSocketStatusListener(SocketStatusListener mSocketStatusListener) {
        this.mSocketStatusListener = mSocketStatusListener;
    }

    private UUSocketIO() {
        this.TAG = "UUSocketIO";
        this.seqId = new AtomicLong(SystemClock.uptimeMillis());
        this.executor = Executors.newSingleThreadScheduledExecutor();
        this.taskes = new HashMap();
        this.SUCCESS_HANDLE = 1;
        this.ERROR_HANDLE = 2;
        this.authTimes = 0;
        this.needReConn = true;
        this.mHandler = new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                int i = msg.what;
                CallbackDataWrapper successWrapper;
                if (i == 1) {
                    successWrapper = msg.obj;
                    successWrapper.getCallback().onSuccess(successWrapper.getData());
                } else if (i == 2) {
                    successWrapper = msg.obj;
                    successWrapper.getCallback().onFail((String) successWrapper.getData());
                }
            }
        };
        this.heartbeatFailCount = 0;
        this.sendTime = 0;
        this.heartbeatTask = new C03902();
        this.reconnectCount = 0;
        this.minInterval = 3000;
        this.maxInterval = FileWatchdog.DEFAULT_DELAY;
        this.mReconnectTask = new C03913();
    }

    public static UUSocketIO getInstance() {
        return WsManagerHolder.mInstance;
    }

    public void setmContext(Context mContext) {
        this.mContext = mContext;
    }

    public void init() {
        try {
            String configUrl = "";
            this.url = TextUtils.isEmpty(configUrl) ? DEF_URL : configUrl;
            WebSocket missingCloseFrameAllowed = new WebSocketFactory().createSocket(this.url, 5000).setFrameQueueSize(5).setMissingCloseFrameAllowed(false);
            WebSocketListener wsListener = new WsListener();
            this.mListener = wsListener;
            this.ws = missingCloseFrameAllowed.addListener(wsListener).connectAsynchronously();
            setStatus(WsStatus.CONNECTING);
            Log.i("UUSocketIO", "第一次连接");
            this.authTimes = 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doAuth() {
        Object bindAction = new BindAction();
        bindAction.setType(Constans.ACTION_LOGIN);
        bindAction.setKey(AbSharedUtil.getString(CustomApplcation.getContext(), "signkey"));
        sendReq(new Gson().toJson(bindAction));
    }

    private void startHeartbeat() {
        this.mHandler.postDelayed(this.heartbeatTask, HEARTBEAT_INTERVAL);
    }

    private void cancelHeartbeat() {
        this.heartbeatFailCount = 0;
        this.mHandler.removeCallbacks(this.heartbeatTask);
    }

    public void sendReq(String jsonStr) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("send text = ");
        stringBuilder.append(jsonStr);
        Log.i("UUSocketIO", stringBuilder.toString());
        this.ws.sendText(jsonStr);
    }

    private <T> void sendReq(Action action, T req, int reqCount) {
        if (isNetConnect()) {
            if (WsStatus.AUTH_SUCCESS.equals(getStatus()) || Action.LOGIN.equals(action)) {
                Object request = new Builder().action(action.getAction()).reqEvent(action.getReqEvent()).seqId(this.seqId.getAndIncrement()).reqCount(reqCount).req(req).build();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("send text :");
                stringBuilder.append(new Gson().toJson(request));
                Log.i("UUSocketIO", stringBuilder.toString());
                this.ws.sendText(new Gson().toJson(request));
            }
        }
    }

    private void setStatus(WsStatus status) {
        this.mStatus = status;
    }

    public WsStatus getStatus() {
        return this.mStatus;
    }

    public void disconnect() {
        WebSocket webSocket = this.ws;
        if (webSocket != null) {
            webSocket.disconnect();
        }
    }

    public void reconnect() {
        if (getStatus() != WsStatus.CONNECT_SUCCESS) {
            String str = "UUSocketIO";
            if (isNetConnect()) {
                WebSocket webSocket = this.ws;
                if (!(webSocket == null || webSocket.isOpen() || getStatus() == WsStatus.CONNECTING)) {
                    this.reconnectCount++;
                    setStatus(WsStatus.CONNECTING);
                    cancelHeartbeat();
                    long reconnectTime = this.minInterval;
                    int i = this.reconnectCount;
                    if (i > 3) {
                        this.url = DEF_URL;
                        long temp = this.minInterval * ((long) (i - 2));
                        long j = this.maxInterval;
                        if (temp <= j) {
                            j = temp;
                        }
                        reconnectTime = j;
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("准备开始第");
                    stringBuilder.append(this.reconnectCount);
                    stringBuilder.append("次重连,重连间隔");
                    stringBuilder.append(reconnectTime);
                    stringBuilder.append("-- url:");
                    stringBuilder.append(this.url);
                    Log.i(str, stringBuilder.toString());
                    this.mHandler.postDelayed(this.mReconnectTask, reconnectTime);
                }
                return;
            }
            this.reconnectCount = 0;
            String str2 = "重连失败网络不可用";
            Log.i(str, str2);
            MainActivity.sendmsg(str2);
        }
    }

    public void cancelReconnect() {
        this.reconnectCount = 0;
        this.mHandler.removeCallbacks(this.mReconnectTask);
    }

    public boolean isNetConnect() {
        ConnectivityManager connectivity = (ConnectivityManager) CustomApplcation.getContext().getSystemService("connectivity");
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected() && info.getState() == State.CONNECTED) {
                return true;
            }
        }
        return false;
    }

    private void msgFromSever(String text) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("receiverMsg:");
        stringBuilder.append(text);
        Log.i("UUSocketIO", stringBuilder.toString());
        try {
            dealTaskMsg(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dealTaskMsg(String text) {
        BaseAction baseAction = (BaseAction) new Gson().fromJson(text, BaseAction.class);
        if (baseAction != null) {
            if (baseAction.getType() != null) {
                String type = baseAction.getType();
                if (Constans.ACTION_REQ_QRCODE.equals(type)) {
                    dealReqQrcodeAction(text);
                } else if (Constans.ACTION_PING.equals(type)) {
                    dealPingAction(baseAction);
                } else if (Constans.ACTION_ERROR.equals(type)) {
                    dealErrorMsg(text);
                } else if ("msg".equals(type)) {
                    dealTipsMsg(text);
                }
            }
        }
    }

    private void dealTipsMsg(String text) {
        PayHelperUtils.sendmsg(CustomApplcation.getContext(), ((TipsAction) new Gson().fromJson(text, TipsAction.class)).getMsg());
    }

    private void dealErrorMsg(String text) {
        if (this.authTimes >= 3) {
            disconnect();
            cancelReconnect();
            this.needReConn = false;
            MainActivity.sendmsg("连接错误,请检查配置的key是否正确");
            this.authTimes = 0;
            return;
        }
        PayHelperUtils.sendmsg(CustomApplcation.getContext(), ((TipsAction) new Gson().fromJson(text, TipsAction.class)).getMsg());
        doAuth();
        this.authTimes++;
    }

    private void dealPingAction(BaseAction baseAction) {
        this.ws.sendText(new Gson().toJson(new BaseAction("pong")));
    }

    private void dealReqQrcodeAction(String text) {
        TaskResonse taskResponse = (TaskResonse) new Gson().fromJson(text, TaskResonse.class);
        if (taskResponse.getData() != null) {
            String mark = taskResponse.getData().getOut_trade_no();
            this.taskes.put(mark, new TimeOutWrapper(taskResponse, enqueueTimeout(mark, REQUEST_TIMEOUT)));
            ContentValues cv = new ContentValues();
            cv.put("money", taskResponse.getData().getMoney());
            cv.put("mark", mark);
            cv.put("type", taskResponse.getData().getType());
            WebSocketAction.GetQrCode(CustomApplcation.getContext(), cv);
        }
    }

    public void sendQrResult(QrcodeResponse qrcodeResponse) {
        WebSocket webSocket = this.ws;
        if (webSocket != null) {
            if (webSocket.getState().equals(WebSocketState.OPEN)) {
                String resResult = new Gson().toJson((Object) qrcodeResponse);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("sendQrResult:");
                stringBuilder.append(resResult);
                Log.i("UUSocketIO", stringBuilder.toString());
                this.ws.sendText(resResult);
                removeTask(qrcodeResponse);
                PayHelperUtils.startAPP();
            }
        }
    }

    private void removeTask(QrcodeResponse qrcodeResponse) {
        TimeOutWrapper wrapper = (TimeOutWrapper) this.taskes.remove(qrcodeResponse.getData().getOut_trade_no());
        if (wrapper != null) {
            wrapper.getTimeoutTask().cancel(true);
        }
    }

    private ScheduledFuture enqueueTimeout(final String seqId, long timeout) {
        return this.executor.schedule(new Runnable() {
            public void run() {
                TimeOutWrapper wrapper = (TimeOutWrapper) UUSocketIO.this.taskes.remove(seqId);
                if (wrapper != null) {
                    if (wrapper.getTaskResonse() != null) {
                        TaskResonse taskResonse = wrapper.getTaskResonse();
                        ContentValues cv = new ContentValues();
                        cv.put("money", taskResonse.getData().getMoney());
                        cv.put("mark", taskResonse.getData().getOut_trade_no());
                        cv.put("type", taskResonse.getData().getType());
                        WebSocketAction.GetQrCode(CustomApplcation.getContext(), cv);
                    }
                }
            }
        }, timeout, TimeUnit.MILLISECONDS);
    }
}

WEBSOCKETACTION

package com.tools.payhelper.socket;

import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
import com.tools.payhelper.utils.PayHelperUtils;

public class WebSocketAction {
    private static String TAG = "WebSocketAction";
    Context context;

    public WebSocketAction(Context context) {
        this.context = context;
    }

    public static void GetQrCode(Context context, ContentValues params) {
        StringBuilder stringBuilder;
        String money = (String) params.get("money");
        String mark = (String) params.get("mark");
        String type = (String) params.get("type");
        if (type == null || type.equals("")) {
            type = "wxpay";
        }
        double m = Double.parseDouble(money);
        String str = "alipay";
        String str2 = "qqpay";
        String str3 = "wxpay";
        if (type.equals(str)) {
            if (m > 50000.0d) {
                PayHelperUtils.sendmsg(context, "支付宝最大支持单笔50000元支付!");
                return;
            }
        } else if (type.equals(str3)) {
            if (m > 15000.0d) {
                PayHelperUtils.sendmsg(context, "微信最大支持单笔15000元支付!");
                return;
            }
        } else if (type.equals(str2)) {
            if (m > 30000.0d) {
                PayHelperUtils.sendmsg(context, "QQ最大支持单笔30000元支付!");
                return;
            } else if (mark.length() > 12) {
                PayHelperUtils.sendmsg(context, "QQ备注长度不能超过12位!");
                return;
            }
        }
        if (type.equals(str)) {
            str = "com.eg.android.AlipayGphone";
            if (!PayHelperUtils.isAppRunning(context, str)) {
                PayHelperUtils.startAPP(context, str);
                str = TAG;
                stringBuilder = new StringBuilder();
                stringBuilder.append("sendAppMsg...");
                stringBuilder.append(params.toString());
                Log.i(str, stringBuilder.toString());
                PayHelperUtils.sendAppMsg(money, mark, type, context);
            }
        }
        if (type.equals(str3)) {
            str = "com.tencent.mm";
            if (!PayHelperUtils.isAppRunning(context, str)) {
                PayHelperUtils.startAPP(context, str);
                str = TAG;
                stringBuilder = new StringBuilder();
                stringBuilder.append("sendAppMsg...");
                stringBuilder.append(params.toString());
                Log.i(str, stringBuilder.toString());
                PayHelperUtils.sendAppMsg(money, mark, type, context);
            }
        }
        if (type.equals(str2)) {
            str = "com.tencent.mobileqq";
            if (!PayHelperUtils.isAppRunning(context, str)) {
                PayHelperUtils.startAPP(context, str);
            }
        }
        str = TAG;
        stringBuilder = new StringBuilder();
        stringBuilder.append("sendAppMsg...");
        stringBuilder.append(params.toString());
        Log.i(str, stringBuilder.toString());
        PayHelperUtils.sendAppMsg(money, mark, type, context);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
/** * 微信支付帮助库 * ==================================================== * 接口分三种类型: * 【请求型接口】--Wxpay_client_ * 统一支付接口类--UnifiedOrder * 订单查询接口--OrderQuery * 退款申请接口--Refund * 退款查询接口--RefundQuery * 对账单接口--DownloadBill * 短链接转换接口--ShortUrl * 【响应型接口】--Wxpay_server_ * 通用通知接口--Notify * Native支付——请求商家获取商品信息接口--NativeCall * 【其他】 * 静态链接二维码--NativeLink * JSAPI支付--JsApi * ===================================================== * 【CommonUtil】常用工具: * trimString(),设置参数时需要用到的字符处理函数 * createNoncestr(),产生随机字符串,不长于32位 * formatBizQueryParaMap(),格式化参数,签名过程需要用到 * getSign(),生成签名 * arrayToXml(),array转xml * xmlToArray(),xml转 array * postXmlCurl(),以post方式提交xml到对应的接口url * postXmlSSLCurl(),使用证书,以post方式提交xml到对应的接口url */ include_once("SDKRuntimeException.php"); include_once("WxPay.pub.config.php"); /** * 所有接口的基类 */ class Common_util_pub { function __construct() { } function trimString($value) { $ret = null; if (null != $value) { $ret = $value; if (strlen($ret) == 0) { $ret = null; } } return $ret; } /** * 作用:产生随机字符串,不长于32位 */ public function createNoncestr( $length = 32 ) { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $str =""; for ( $i = 0; $i $v) { if($urlencode) { $v = urlencode($v); } //$buff .= strtolower($k) . "=" . $v . "&"; $buff .= $k . "=" . $v . "&"; } $reqPar; if (strlen($buff) > 0) { $reqPar = substr($buff, 0, strlen($buff)-1); } return $reqPar; } /** * 作用:生成签名 */ public function getSign($Obj) { foreach ($Obj as $k => $v) { $Parameters[$k] = $v; } //签名步骤一:按字典序排序参数 ksort($Parameters); $String = $this->formatBizQueryParaMap($Parameters, false)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

侠客软件开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值