Android websocket使用


源碼地址

gitHub地址 https://github.com/crossbario/autobahn-java

支持wss和ws

 

1、添加依賴:

dependencies {
    implementation 'io.crossbar.autobahn:autobahn-android:18.5.1'
}

可能遇到的問題 1

解決辦法:(1)修改 minSdkVersion = 24
解決辦法:(2)AndroidManifest.xml 中添加 <uses-sdk tools:overrideLibrary="io.crossbar.autobahn"/>

可能遇到的問題 2

解決辦法:

在Android{ } 中加入了

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

2,簡單使用介紹

public class MyWebSocketManager {
 
    private volatile static MyWebSocketManager webSocketManager;
    private WebSocketConnection wsc;
 
    private MyWebSocketManager() {
    }
 
    public static MyWebSocketManager getInstance() {
        if (webSocketManager == null) {
            synchronized (MyWebSocketManager.class) {
                if (webSocketManager == null) {
                    webSocketManager = new MyWebSocketManager();
                }
            }
        }
        return webSocketManager;
    }
 
    public void connReceiveWebSocketData() {
        if (null == wsc) {
            wsc = new WebSocketConnection();
        }
        WebSocketOptions mWebSocketOptions = new WebSocketOptions();
        mWebSocketOptions.setMaxFramePayloadSize(1024 * 1024 * 2);
 
        //重連間隔
        mWebSocketOptions.setReconnectInterval(10000);
 
        try {
            wsc.connect( "wss://message.yunke.com/message.plan.ws", new WebSocketConnectionHandler() {
 
                @Override
                public void onOpen() {
                    //第一次建立連接要發送的參數
                    final String message = getJsonString();
                    if (wsc != null && message != null) {
                        try {
                            wsc.sendMessage(message);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
 
                @Override
                public void onMessage(final String payload) {
                }
 
                @Override
                public void onClose(int code, String reason) {
                }
 
            }, mWebSocketOptions);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private String getJsonString() {
        WebSocketParamsEnty mWebSocketParamsEnty = new WebSocketParamsEnty();
        Gson gson = new Gson();
        String message = gson.toJson(mWebSocketParamsEnty);
        return message;
    }
 
    /**
     * 關閉WebSocket
     */
    public void closeWebSocket() {
        if (wsc != null) {
            wsc.sendClose();
        }
    }
 
}

 

參考於:https://blog.csdn.net/qq_32671919/article/details/81221226


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM