android开发使用OkHttp自带的WebSocket实现IM功能

一、背景

android app开发经常会有IM需求,很多新手不晓得如何入手,难点在于通讯不中断。其实android发展到今天,很多技术都很完善,有很多类似框架可以实现。例如有:okhttp自带的websocket框架、easysocket等等。本文主要讨论的是okhttp自带的websocket框架。

二、在项目中添加依赖包

复制代码
implementation 'com.squareup.okhttp3:mockwebserver:3.8.1'

三、框架调用

1、配置OkHttpClient

websocket断线重连配置pingInterval即可,实现非常之方便。第一个参数为数字,第二个为单位一般设置秒(s)。

pingInterval(HEART_BEAT_RATE, TimeUnit.SECONDS)//设置心跳

复制代码
OkHttpClient mClient = new OkHttpClient.Builder()
        .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
        .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
        .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
        .pingInterval(HEART_BEAT_RATE, TimeUnit.SECONDS)//设置心跳
        .build();

2、调用Url,构建WebSocket请求

复制代码
//websocket地址
String url = "ws://xxxxx"

//创建请求对象
Request request = new Request
                        .Builder()
                        .get()
                        .url(url)
                        .build();

3、建立连接

方法说明

  • onOpen(),连接成功

  • onMessage(String text),收到字符串类型的消息

  • onMessage(ByteString bytes),收到字节数组类型消息

  • onClosed(),连接关闭

  • onFailure(),连接失败

    //开始连接
    WebSocket websocket = mClient.newWebSocket(request, new WebSocketListener() {
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
    super.onOpen(webSocket, response);
    //连接成功...
    }

    复制代码
      @Override
      public void onMessage(WebSocket webSocket, String text) {
          super.onMessage(webSocket, text);
          //收到消息
      }
    
      @Override
      public void onMessage(WebSocket webSocket, ByteString bytes) {
          super.onMessage(webSocket, bytes);
          //收到消息
      }
    
      @Override
      public void onClosed(WebSocket webSocket, int code, String reason) {
          super.onClosed(webSocket, code, reason);
          //连接关闭...
      }
    
      @Override
      public void onFailure(WebSocket webSocket, Throwable throwable, Response response) {
          super.onFailure(webSocket, throwable, response);
          //连接失败...
      }

    });

4、使用WebSocket对象发送消息

复制代码
JSONObject jsonObject = new JSONObject();
            jsonObject.put("xxxxxx", xxxxx);

//发送消息            
websocket.send(jsonObject.toString());

最后推荐一个android 开发ui框架**XUI - Android 原生 UI 框架,**很多简单的ui都有对应的框架。

相关推荐
爱勇宝8 小时前
我做了一个只用来搜歌词的小 App
android·前端·后端
众少成多积小致巨12 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
Coffeeee18 小时前
如何使用Glide和Coil加载WebP动图
android·kotlin·glide
Kapaseker19 小时前
5 分钟搞懂 Kotlin DSL
android·kotlin
恋猫de小郭19 小时前
AI Agent 开发究竟是啥?如何用 AI 开发 Agent ?深入浅出给你一套概念
android·前端·ai编程
黄林晴20 小时前
Android 17 正式发布!target 37 一大批旧代码直接不能用了
android
Carson带你学Android20 小时前
Android 17 正式发布:AI 终于成了系统能力
android·前端·ai编程
三少爷的鞋20 小时前
当 UseCase 开始长期监听,它可能已经不是 UseCase 了
android
恋猫de小郭1 天前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
恋猫de小郭1 天前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter