美文网首页
WebScoket建立连接,发送消息和接收消息功能

WebScoket建立连接,发送消息和接收消息功能

作者: 小婷android | 来源:发表于2021-11-23 08:52 被阅读0次

主要采用的是第三方的一个websocket库libs/autobahn-0.5.0.jar

建立工具类websocket类

public class MonitorSocketService extends Service {
  public static String WEB_SOCKET_HOST = "";//这个是后台给的地址
    private static final String TAG = "MonitorSocketService";
    private static WebSocketConnection webSocketConnection; // ws 对应的类
    private static WebSocketOptions options = new WebSocketOptions(); //ws的个选项,声明出来即可使用了
    private boolean isOpen;//ws打开的状态
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }


    @Override
    public void onCreate() {
        super.onCreate();
        webSocketConnect();
        LogUtils.debug(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.debug(TAG, "onStartCommand");
        webSocketConnect();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWebsocket();
        LogUtils.debug(TAG, "onDestroy");
    }

    // 这里使用binder 主要是为了在activity中进行通讯, 大家也可以使用EventBus进行通讯
    public class MyBinder extends Binder {

        public MonitorSocketService getService() {
            return MonitorSocketService.this;
        }
    }

    /**
     * 连接ws
     */
    public void webSocketConnect() {

        webSocketConnection = new WebSocketConnection();
        try {
            webSocketConnection.connect(WEB_SOCKET_HOST, new WebSocketHandler() {

                //websocket启动时候的回调
                @Override
                public void onOpen() {
                    LogUtils.debug(TAG, "onOpen");
                    isOpen = true;
                }

                //websocket接收到消息后的回调
                @Override
                public void onTextMessage(String content) {
                    LogUtils.debug(TAG, "onTextMessage");
                    //这里可以使用EventBus将内容传递到activity
                    if (mListener != null) {
                        mListener.onTextMsg(content);
                    }

                }

                //websocket关闭时候的回调
                @Override
                public void onClose(int code, String reason) {
                    LogUtils.debug(TAG, "onClose" + reason);
                    isOpen = false;
                }

            }, options);
        } catch (WebSocketException e) {
            e.printStackTrace();
            isOpen = false;
            closeWebsocket();
        }
    }

    /**
     * 关闭ws
     */
    public void closeWebsocket() {
        if (webSocketConnection != null && webSocketConnection.isConnected()) {
            webSocketConnection.disconnect();
            webSocketConnection = null;
        }
    }

    /**
     * ws是否连接
     *
     * @return
     */
    public boolean isOpen() {
        return isOpen;
    }

    /**
     * 发送信息,
     *
     * @param s
     */
    public void sendMsg(String s) {
        if (webSocketConnection != null && isOpen) {
            webSocketConnection.sendTextMessage(s);
            LogUtils.debug(TAG, "sendMsg");
        }
    }

    //在service中创建回调接口
    private OnDataReceiverListener mListener;

    //设置监听
    public void setOnDataReceiverListener(OnDataReceiverListener listener) {
        mListener = listener;
    }


    public interface OnDataReceiverListener {
        void onTextMsg(String text);
    }
}

具体项目中的引用

onResume方法中
  @Override
    public void onResume() {
        super.onResume();
        Intent intent = new Intent(getActivity(), MonitorSocketService.class);
        getActivity().bindService(intent, mConnection, BIND_AUTO_CREATE);
    }

 //得到service的对象后,调用发送信息方法即可
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.debug("TAG", "onServiceConnected:");
            MonitorSocketService.MyBinder binder = (MonitorSocketService.MyBinder) service;
            mService = binder.getService();
            mService.setOnDataReceiverListener(text -> {
             //用来接收消息实时更新的
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.debug("TAG", "onServiceDisconnected:");
        }
    };

//发送消息
mService.sendMsg();

相关文章

网友评论

      本文标题:WebScoket建立连接,发送消息和接收消息功能

      本文链接:https://www.haomeiwen.com/subject/qlaitrtx.html