websocket请求


直接使用开源库:https://github.com/koush/AndroidAsync
上面那个好像只能建立websocket服务。我们换一个吧。。

https://github.com/TakahikoKawasaki/nv-websocket-client

参考代码如下:

package com.xiaoyou.xblog.tools;

import android.util.Log;

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 java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * websocket管理类,用于管理websocket请求
 * @author 小游
 */
public class WebSocketManage{
    /**连接超时时间*/
    private static final int DEFAULT_CONNECT_TIMEOUT=3000;
    /**重连超时时间*/
    private static final int DEFAULT_RECONNECT_TIMEOUT=3000;
    /**队列长度*/
    private static final int FRAME_QUEUE_SIZE = 5;
    private WebSocketListener mWebSocketListener;
    private WebSocketFactory mWebSocketFactory;
    private WebSocket mWebSocket;

    private ConnectStatus mConnectStatus = ConnectStatus.CONNECT_DISCONNECT;

    private String mUri;

    public interface WebSocketListener {
        void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception;

        void onTextMessage(WebSocket websocket, String text) throws Exception;
    }

    public enum ConnectStatus {
        // 断开连接
        CONNECT_DISCONNECT,
        //连接成功
        CONNECT_SUCCESS,
        //连接失败
        CONNECT_FAIL,
        //正在连接
        CONNECTING
    }

    public WebSocketManage(String uri) {
        this(uri,DEFAULT_CONNECT_TIMEOUT);
    }

    private WebSocketManage(String uri, int timeout) {
        mUri = uri;
        mWebSocketFactory = new WebSocketFactory().setConnectionTimeout(timeout);
    }

    public void setWebSocketListener(WebSocketListener webSocketListener) {
        mWebSocketListener = webSocketListener;
    }

    public void connect() {
        try {
            mWebSocket = mWebSocketFactory.createSocket(mUri)
                    .setFrameQueueSize(FRAME_QUEUE_SIZE)//设置帧队列最大值为5
                    .setMissingCloseFrameAllowed(false)//设置不允许服务端关闭连接却未发送关闭帧
                    .addListener(new NVWebSocketListener())
                    .connectAsynchronously();
            setConnectStatus(ConnectStatus.CONNECTING);
        } catch (IOException e) {
            e.printStackTrace();
//            reconnect();
        }
    }

    private void setConnectStatus(ConnectStatus connectStatus) {
        mConnectStatus = connectStatus;
    }

    public ConnectStatus getConnectStatus() {
        return mConnectStatus;
    }

    public void disconnect() {
        if (mWebSocket != null) {
            mWebSocket.disconnect();
        }
        setConnectStatus(null);
    }

    class NVWebSocketListener extends WebSocketAdapter{
        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
            super.onConnected(websocket, headers);
            Log.e("xblog","OS. WebSocket onConnected");
            setConnectStatus(ConnectStatus.CONNECT_SUCCESS);
            if (mWebSocketListener != null) {
                mWebSocketListener.onConnected(websocket, headers);
            }
        }

        @Override
        public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
            super.onConnectError(websocket, exception);
            Log.e("xblog","OS. WebSocket onConnectError"+exception.getMessage());
            setConnectStatus(ConnectStatus.CONNECT_FAIL);
        }

        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            Log.e("xblog","OS. WebSocket onDisconnected");
            setConnectStatus(ConnectStatus.CONNECT_DISCONNECT);
//            reconnect();
        }

        @Override
        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            super.onTextMessage(websocket, text);
            System.out.println("OS. WebSocket onTextMessage");
            if (mWebSocketListener != null) {
                mWebSocketListener.onTextMessage(websocket, text);
            }
        }
    }

//    public void reconnect() {
//        if (mWebSocket != null && !mWebSocket.isOpen() && getConnectStatus() != ConnectStatus.CONNECTING) {
//            mReconnectTimerTask = new TimerTask() {
//                @Override
//                public void run() {
//                    connect();
//                }
//            };
//            ewScheduledThreadPool.schedule(mReconnectTimerTask,DEFAULT_RECONNECT_TIMEOUT,TimeUnit.MILLISECONDS);
//        }
//    }

}

okhttp好像也可以建立websocket请求,具体可以查看下面的文章:(但是我测试报错了,说什么403错误。。。)
https://www.jianshu.com/p/e294e6baa158

最后发现是我的锅。。。好像用别人的就没问题。。。好像是echo的net库的websockt库在安卓上用不了。。。(看来新技术真的有好多缺点啊~~ ~)

后面就要改自己的后端框架了。。太难了我。。。

最后我还是打算用okhttp


文章作者: 小游
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小游 !
  目录