//okhttp
implementation(“com.squareup.okhttp3:okhttp:4.9.0”)
private WebSocketListener socketListener = new WebSocketListener() {
//回调监听@Overridepublic void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
Log.e(TAG, "connect onClosed");}@Overridepublic void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
Log.e(TAG, "connect onFailure " + t.toString());}@Overridepublic void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
Log.e(TAG, "connect onMessage String : " + text);}@Overridepublic void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
Log.e(TAG, "connect onMessage ByteString");}@Overridepublic void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
Log.e(TAG, "connect onMessage onOpen");mWebSocket = webSocket;}};@Overridepublic void connect() {
//建立连接String wsUrl = "ws://xxx.xxx.xxx"Log.e(TAG, "connect : " + wsUrl);if(TextUtils.isEmpty(wsUrl)) {
throw new RuntimeException("Wc Connection url is empty");}OkHttpClient mClient = new OkHttpClient.Builder().pingInterval(5, TimeUnit.SECONDS).build();Request request = new Request.Builder().url(wsUrl).build();mClient.newWebSocket(request, socketListener);}@Overridepublic boolean send(String msg) {
//发送数据if(mWebSocket == null) return false;boolean send = mWebSocket.send(msg);return send;}