Android 之WebSocket 通信

最近在做使用三方im做一些业务的时候,领导觉得三方的im通信并不能很好的适应我们的需求。
所以决定抽时间,自己使用WebSocket实现一个长链接。
做之前肯定要逛一逛github,学习一下优秀的经验,不经意间就找到了 Java-WebSocket,秉着这不重复制造轮的理论,直接上手使用起来。

Gradle 使用

mavenCentral()
implementation 'org.java-websocket:Java-WebSocket:1.5.1'

创建WebSocketChatClient继承WebSocketClient

public class WebSocketChatClient extends WebSocketClient {

    public WebSocketChatClient(URI serverUri) {
        super(serverUri);
    }

    public WebSocketChatClient(URI serverUri, Draft draft) {
        super(serverUri, draft);
    }

    public WebSocketChatClient(URI serverUri, Map httpHeaders) {
        super(serverUri, httpHeaders);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("WebSocketChatClient Connected");

    }

    @Override
    public void onMessage(String message) {
        System.out.println("WebSocketChatClient got: " + message);

    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocketChatClient Disconnected");

    }

    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
        System.out.println("WebSocketChatClient onError");
    }
}

然后初始化WebSocketChatClient

var str: String? =
    "ws://robot-app.wondertemple.com:8058/4419a2e94b2b9cd2bde7f8103dfa5b25"
var chatClient: WebSocketChatClient? = null

chatClient = WebSocketChatClient(URI(str))
chatClient?.connect()

链接成功,后台返回

com.example.socketdemo I/System.out: WebSocketChatClient Connected
com.example.socketdemo I/System.out: WebSocketChatClient got: {"cmd":"connection","data":{"message":"ok"}}

断开连接

chatClient?.close()

重连

chatClient?.reconnect()

发送消息

chatClient?.send(JSONObject.toJSONString(msgBean))

至此,一个简单的im 基础功能就完成了,后边大家就可以慢慢扩展了

你可能感兴趣的:(Android 之WebSocket 通信)