Android开发-WebSocketWssDemo

Android 专栏收录该内容
170 篇文章 0 订阅

Android连接一个类似于 wss://www.ceshi.com:8084 这样的WebSocket服务器

 

依赖:

    implementation 'org.java-websocket:Java-WebSocket:1.4.1'

代码:

package com.iwanghang.websocketwssdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.helpers.Util;

import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MainActivity extends AppCompatActivity {

    private Handler handler;
    private WebSocketClient mSocketClient;
    public static final String socket_rul = "wss://www.ceshi.com:8084"; // WebSocket测试地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void initWebSocket() {
        try {
            Log.i("WebSocketWssDemo", "init");
            mSocketClient = new WebSocketClient(URI.create(socket_rul), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) { // 打开通道
                    Log.i("WebSocketWssDemo", "onOpen\n" + handshakedata);
                    handler.obtainMessage(0, handshakedata).sendToTarget();
                }

                @Override
                public void onMessage(String message) { // 接受服务器信息
                    Log.i("WebSocketWssDemo", "onMessage\n" + message);
                    handler.obtainMessage(0, message).sendToTarget();

                }

                @Override
                public void onClose(int code, String reason, boolean remote) {  // 通道关闭
                    Log.i("WebSocketWssDemo", "onClose\n" + reason);
                    handler.obtainMessage(0, reason).sendToTarget();
                }

                @Override
                public void onError(Exception ex) {
                    Log.i("WebSocketWssDemo", "onError\n" + ex);
                }

            };
            // wss需添加
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }
                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            SSLSocketFactory factory = sslContext.getSocketFactory();
            mSocketClient.setSocketFactory(factory);
            mSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSocketClient != null){
            mSocketClient.close();
        }
    }

    public void sendMessageClick(View view) {
        if (mSocketClient != null){
            mSocketClient.send("join");
        }

    }

    @SuppressLint("HandlerLeak")
    public void initWebSocketClientClick(View view) {

        initWebSocket();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.i("WebSocketWssDemo", msg.toString());
            }
        };

    }


}

权限:

    <uses-permission android:name="android.permission.INTERNET" />

界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:onClick="initWebSocketClientClick"
        android:text="初始化"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>

    <Button
        android:onClick="sendMessageClick"
        android:text="发消息"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>

</LinearLayout>

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值