Android使用WebSocket

  • Post author:
  • Post category:其他




1、WeoSocket的引入

在Android项目的build.gradle中加入:

implementation "org.java-websocket:Java-WebSocket:1.5.2"

Sync一下极氪将websocket引入我们这个项目



2、编码

  1. 首先创建一个类WebSocketServer 继承 WebSocket包提供的 WebSocketClient 类
public class WebSocketServer extends WebSocketClient {

    @Override
    protected void onSetSSLParameters(SSLParameters sslParameters) {
    
    }

    public WebSocketServer(URI uri) {
        super(uri, new Draft_6455());
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.e("WebSocket", "connect");
    }

    @Override
    public void onMessage(String message) {
        Log.e("WebSocket", message);

    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.e("WebSocket", reason);
    }

    @Override
    public void onError(Exception ex) {
        Log.e("WebSocket", ex.toString());
    }
}
  1. 创建一个service去实现我们刚刚创建的类
public class WebSocketService extends Service {

    private final static String TAG = "WebSocketClient";

    public static boolean isRunning = false;

    private URI uri;

    public WebSocketServer client;

    private WebSocketClientBinder mBinder = new WebSocketClientBinder();

    //设置intent用来向MainActivity传递消息修改UI
    private Intent intent = new Intent("com.caisang");

    //用于Activity和service通讯
    public class WebSocketClientBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initSocketClient();
        //开启心跳检测
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (client != null && client.isOpen()) {
			//启动service时调用,可以检查websocket此时状态
        }
        return START_STICKY;
    }

    public static class GrayInnerService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(GRAY_SERVICE_ID, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

    @Override
    public void onDestroy() {
        closeConnect();
        LogUtils.w("ws被销毁");
        super.onDestroy();
    }

    private void initSocketClient() {
        URI uri = URI.create(Wsutil.ws + Wsutil.devicesID);
        Log.i(TAG,"正在连接服务:"+Wsutil.ws);
        client = new WebSocketServer(uri) {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onMessage(String message) {
            //这个是我自己封装的消息类
                DeviceMessage deviceMessage = JSON.parseObject(message,DeviceMessage.class);
                LogUtil.e(TAG, "收到消息,消息内容是:" + deviceMessage );
                

                }
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {时调用
                LogUtil.e(TAG, "onClose() 连接断开_reason:" + reason);

                mHandler.removeCallbacks(heartBeatRunnable);
                //开启心跳检测
                mHandler.postDelayed(heartBeatRunnable, CLOSE_RECON_TIME);
            }

            @Override
            public void onError(Exception ex) {
                LogUtil.e(TAG, "onError() 连接出错:" + ex.getMessage());

                mHandler.removeCallbacks(heartBeatRunnable);
                //开启心跳检测
                mHandler.postDelayed(heartBeatRunnable, CLOSE_RECON_TIME);
            }
        };
        connect();
    }

    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
    
    public void sendMsg(String msg) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (null != client && client.isOpen()) {
                    client.send(msg);
                }
            }
        }).start();
    }

    private void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }

	//每隔10秒进行一次对长连接的心跳检测
    private static final long HEART_BEAT_RATE = 10 * 1000;
    private final Handler mHandler = new Handler();
    private final Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }
            } else {
                //如果client已为空,重新初始化连接
                initSocketClient();
            }
            //每隔一定的时间,对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Log.e("Websocket", "开启重连");
                    client.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

3.在需要的地方绑定和启动这个service

	private Context mContext;
	mContext = getApplication();
	//启动服务
    private void startWebSClientService() {
        Intent intent = new Intent(mContext, WebSocketService.class);
        startService(intent);
    }
    //绑定服务
    private void bindService() {
        Intent bindIntent = new Intent(mContext, WebSocketService.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("MainActivity", "服务与活动成功绑定");
            WebSClientService = ((WebSocketService.WebSocketClientBinder) iBinder).getService();
            client = WebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("MainActivity", "服务与活动成功断开");
        }
    };
    //取消服务绑定
    unbindService(serviceConnection);
  1. 启动整个项目,见到

    E/MainActivity: 服务与活动成功绑定

    ,服务成功启动,完成



版权声明:本文为weixin_49855330原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。