Android开发-WebSocketWssDemo

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());
            }
        };

    }


}

权限:

    

界面:




    

 

你可能感兴趣的:(Android)