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 中添加

Android websocket使用_第1张图片

可能遇到的问题 2

解决办法:

Android websocket使用_第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

你可能感兴趣的:(Android websocket使用)